我有一个对象列表(survey::svyciprop 的输出),我正在尝试提取它们的属性以创建包含所有结果的数据框。
#example of an object
props_and_cis[[1]]
2.5% 97.5%
var1 0.932 0.826 0.98
我已经想出如何在单独的列中提取我想要的每个项目:
var <- attr(props_and_cis[[1]],"names")
prop <- as.vector(props_and_cis[[1]])
ci_lower <- attr(props_and_cis[[1]], "ci")[1]
ci_upper <- attr(props_and_cis[[1]], "ci")[2]
我想遍历列表中的每个对象
props_and_cis
并将提取的内容写入数据框,例如:
tribble(
~variable, ~prop, ~ci_lower, ~ci_upper,
var,prop,ci_lower,ci_upper
)
但我似乎无法让它发挥作用。有人可以帮忙吗?
预计到达时间:
> dput(props_and_cis[[1]])
structure(c(var1 = 0.932403111115339), var = structure(0.00119910004765771, dim = c(1L,
1L), dimnames = list("as.numeric(var1)", "as.numeric(var1)")), ci = c(`2.5%` = 0.825647967272783,
`97.5%` = 0.975715067477937), class = "svyciprop")
写一个函数来提取想要的数据。
extract_attr <- function(x) {
v <- attr(x, "names")
ci <- attr(x, "ci")
y <- cbind(data.frame(var = v, prop = c(x)), as.data.frame(t(ci)))
row.names(y) <- NULL
y
}
extract_attr(props_and_cis[[1]])
#> var prop 2.5% 97.5%
#> 1 var1 0.9324031 0.825648 0.9757151
创建于 2023-03-30 与 reprex v2.0.2
然后
lapply
函数到你的列表成员和rbind
结果得到一个data.frame。在下面的示例中,我重复发布的数据示例,所有列表成员彼此相等。
res <- lapply(props_and_cis, extract_attr)
do.call(rbind, res)
#> var prop 2.5% 97.5%
#> 1 var1 0.9324031 0.825648 0.9757151
#> 2 var1 0.9324031 0.825648 0.9757151
#> 3 var1 0.9324031 0.825648 0.9757151
创建于 2023-03-30 与 reprex v2.0.2
posted <- structure(c(var1 = 0.932403111115339),
var = structure(0.00119910004765771, dim = c(1L, 1L),
dimnames = list("as.numeric(var1)", "as.numeric(var1)")),
ci = c(`2.5%` = 0.825647967272783, `97.5%` = 0.975715067477937),
class = "svyciprop")
props_and_cis <- list(posted, posted, posted)
创建于 2023-03-30 与 reprex v2.0.2