提取data.frame列表的名称以及R中data.frame中的值 [英] Extracting the names of a list of data.frames along with values in the data.frame in R
问题描述
在下面的代码中,j
是data.frames的命名列表.我想知道是否有办法:
In below code, j
is a named list of data.frames. I was wondering if there might be a way to:
(a)提取data.frame内部变量的数值(即one.short
和one.long
),并附加其相关名称(即"AAA"
或"CCC"
)提取的值?
(a) extract the numeric values of the variables (i.e., one.short
and one.long
) inside the data.frames and attach their related names (i.e., "AAA"
or "BBB"
or "CCC"
) to the extracted values?
(b)如果变量(即one.short
或one.long
)是NA
,那么在提取该变量时将该data.frame的名称更改为NA
吗?
(b) if a variable (i.e., one.short
or one.long
) is NA
, then change the name of that data.frame to NA
when extracting that variable?
预期输出:
在下面的示例中,我希望我的输出像这样:
In the below example, I expect my output to be like:
one.short = list(c("AAA", .6), c(NA, NA), c("CCC", .4))
one.long = list(c("AAA", .8), c(NA, NA), c(NA, NA))
R代码和可复制的数据:
j <- list(data.frame(one.short = .6, one.long = .8), data.frame(one.short = NA,
one.long = NA), data.frame(one.short = .4, one.long = NA))
names(j) <- c("AAA", "BBB", "CCC")
# I tried this without success:
one.short = sapply(1:length(j), function(i) j[[i]]$one.short)
one.long = sapply(1:length(j), function(i) j[[i]]$one.long)
推荐答案
我们可以使用[[
来执行此操作而无需匿名功能
We can use the [[
to do this without anonymous function
v1 <- sapply(j, `[[`, 'one.short')
v1
# AAA BBB CCC
# 0.6 NA 0.4
如果我们要设置NA值的名称
If we want to set the names of values that NA
names(v1)[is.na(v1)] <- "NULL"
v1
# AAA NULL CCC
# 0.6 NA 0.4
请注意,NULL
需要放在list
中,因为它会掉入vector
Note that NULL
would need to be in a list
because it gets dropped in a vector
c('a', 'b', NULL)
#[1] "a" "b"
list('a', 'b', NULL)
#[[1]]
#[1] "a"
#[[2]]
#[1] "b"
#[[3]]
#NULL
这篇关于提取data.frame列表的名称以及R中data.frame中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!