【发布时间】:2015-03-24 09:42:08
【问题描述】:
我正在尝试使用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]。 -
嗨,是的.. 你写的正是我所期望的..
dplyr可以做同样的事情吗? -
您可以像
select(df1, matches(paste(vec_fil, collapse = "|")))那样做一些荒谬的事情,但我只是不明白为什么在这种情况下不使用base R。 -
是的,
select(df1, which(names(df1) %in% vec_fil))应该可以完成这项工作 -
太棒了!感谢大家! @Mamoun,如果您发表评论作为答案,我会接受。