May*_*ans 4 r list subset lapply purrr
我有一个数据框列表,我想x
从每个数据框中获取列作为字符串。
testing <- list(data.frame(A = "Yes", B = "No"),
data.frame(B = "No", C = "No"),
data.frame(A = "Yes"))
Run Code Online (Sandbox Code Playgroud)
我可以打印哪些数据帧中有colname
A,但我无法连接到子集原始测试
lapply(testing, function(x) "A" %in% colnames(x))
Run Code Online (Sandbox Code Playgroud)
[[1]]
A B
1 Yes No
[[2]]
A
1 Yes
Run Code Online (Sandbox Code Playgroud)
另一个基本选项是 Filter
out <- Filter(function(x) "A" %in% names(x), testing)
out
#[[1]]
# A B
#1 Yes No
#
#[[2]]
# A
#1 Yes
Run Code Online (Sandbox Code Playgroud)
我们可以sapply
用来创建逻辑vector
和子集
testing[sapply(testing, function(x) "A" %in% colnames(x))]
Run Code Online (Sandbox Code Playgroud)