我想使用dplyr
的select
函数来提取另一个数据框中的列。
这是数据框:
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"))
这里是我想要用作过滤器的字符向量:
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")
正如你所看到的,vec_fil
有许多字符与df1的列不匹配,因此我会得到以下错误:
require("dplyr")
df2 <- select(df1, one_of(vec_fil))
Error: Each argument must yield either positive or negative integers
有什么提示可以帮助我只获取新数据框中过滤向量的匹配字符?
one_of
是从哪里来的?也许你想要做的是df1[, names(df1) %in% vec_fil]
。 - Mamoun Benghezaldplyr
也能做到同样的事情吗? - matteoselect(df1, matches(paste(vec_fil, collapse = "|")))
,但我只是不明白为什么在这种情况下不使用基本的R。 - David Arenburgselect(df1, which(names(df1) %in% vec_fil))
可以完成这个任务。 - Mamoun Benghezal