鑑於這一數據選擇多列變異新列: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