鉴于这一数据选择多列变异新列:dplyr:基于由变量字符串
df=data.frame(
x1=c(2,0,0,NA,0,1,1,NA,0,1),
x2=c(3,2,NA,5,3,2,NA,NA,4,5),
x3=c(0,1,0,1,3,0,NA,NA,0,1),
x4=c(1,0,NA,3,0,0,NA,0,0,1),
x5=c(1,1,NA,1,3,4,NA,3,3,1))
我想创建一个使用dplyr选定列的横行最小值一个额外的列min
。这很容易使用的列名:
df <- df %>% rowwise() %>% mutate(min = min(x2,x5))
但我有一个大的DF具有不同的列名,所以我需要从价值观mycols
的一些字符串匹配。现在其他线程告诉我使用选择帮助函数,但我必须缺少一些东西。下面是matches
:
mycols <- c("x2","x5")
df <- df %>% rowwise() %>%
mutate(min = min(select(matches(mycols))))
Error: is.string(match) is not TRUE
而且one_of
:
mycols <- c("x2","x5")
df <- df %>%
rowwise() %>%
mutate(min = min(select(one_of(mycols))))
Error: no applicable method for 'select' applied to an object of class "c('integer', 'numeric')"
In addition: Warning message:
In one_of(c("x2", "x5")) : Unknown variables: `x2`, `x5`
我是什么俯瞰? select_
应该工作吗?它不会在以下几点:
df <- df %>%
rowwise() %>%
mutate(min = min(select_(mycols)))
Error: no applicable method for 'select_' applied to an object of class "character"
而且同样:
df <- df %>%
rowwise() %>%
mutate(min = min(select_(matches(mycols))))
Error: is.string(match) is not TRUE
您需要使用dplyr动词的SE版本当使用字符串。在这种情况下,使用'select _()' –
不能正常工作,因为我预计它可以工作:'df <- df %>% rowwise()%>% mutate(min = min(select_(mycols)))'yield“Error :没有将'select_'应用于类“字符”类的对象的适用方法“ – strangeloop
由于它将字符串(正则表达式)作为参数而不是字符串向量,因此会出现'matches'错误。 – cderv