我正在尝试使用select函数dplyr来提取另一个数据帧的列.
这里的数据框:
dput(df1)
structure(list(Al = c(30245, 38060, 36280, 24355, 27776, 35190,
38733.8, 36400, 29624, 33699.75), As = c(9, 8.75, 13.5, 7.75,
7.6, 8.33, 8, 8.75, 7.4, 8.25), Cd = c(0.15, 0.13, 0.15, 0.1,
0.16, 0.13, 0.24, 0.15, 0.22, 0.13), Cr = c(108.5, 111.75, 104.5,
81.25, 93.2, 109.75, 105, 104, 87.8, 99.75), Hg = c(0.25, 0.35,
0.48, 1.03, 1.12, 0.2, 1.14, 0.4, 2, 0.48)), row.names = c(NA,
10L), class = "data.frame", .Names = c("Al", "As", "Cd", "Cr",
"Hg"))
Run Code Online (Sandbox Code Playgroud)
这里我想用作过滤器的字符向量:
dput(vec_fil)
c("Elemento", "As", "Cd_totale", "Cr_totale", "Cu_totale", "Hg",
"Ni_totale", "Pb_totale", "Zn_totale", "Composti_organostannici",
"PCB_totali", "Sommatoria_DDD", "Sommatoria_DDE", "Sommatoria_DDT",
"Clordano", "Dieldrin", "Endrin", "Esaclorocicloesano", "Eptacloro_epossido",
"Sommatoria_IPA", "Acenaftene", "Antracene", "Benzo.a.antracene",
"Benzo.a.pirene", "Crisene", "Dibenzo.ac._.ah.antracene", "Fenantrene",
"Fluorantene", "Fluorene", "Naftalene", "Pirene")
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,vec_fil有许多字符与df1的列不匹配,因此我收到此错误:
require("dplyr")
df2 <- select(df1, one_of(vec_fil))
Error: Each argument must yield either positive or negative integers
Run Code Online (Sandbox Code Playgroud)
我可以使用任何提示,以便只获取新数据框中过滤器向量的匹配字符?
您可以在基础R中尝试此代码
df1[, names(df1) %in% vec_fil]
Run Code Online (Sandbox Code Playgroud)
如果你想使用包 dplyr
select(df1, which(names(df1) %in% vec_fil))
Run Code Online (Sandbox Code Playgroud)
我在晚会上迟到了.但是,没有人解释错误的原因是什么.所以,我做到了.
您错误地使用one_of()了dplyr包中的内容.根据包文档,它选择[all]向量中的变量.
one_of("x","y","z"):选择字符向量中提供的变量.
它不允许您从one_of()向量中选择变量的子集,尽管函数的名称暗示了这一点.
在您的情况下,vec_fil向量具有一些在数据框中不存在的要素名称.因此,它会引发错误.只有one_of()当您有一长串功能名称并且您不想手动键入它们时才应该使用.因此,您可以直接从列表中读取它们.
希望它能帮助您完成未来的工作.