dplyr:使用链接来传递变量

use*_*672 5 r chain stringr dplyr

我是新手,dplyr无法弄清楚如何控制变量来通过chaining(%>%)命令.简单的例子:该str_sub函数有三个参数 - 第一个是传递%>%但是如何获得最后两个?:

library(stringr)
library(dplyr)
df <- data.frame(V1 = c("ABBEDHH", "DEFGH", "EFGF", "EEFD"), 
                 V2=c(4, 2, 1, 1), V3=c(5, 2, 2, 1), stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)

在基地RI可以做:

with(df, str_sub(V1, V2, V3))
Run Code Online (Sandbox Code Playgroud)

得到:

## [1] "ED" "E"  "EF" "E" 
Run Code Online (Sandbox Code Playgroud)

如何链接这个?- 我试过了:

df %>% str_sub(V1, V2, V3) # Here V3 is unused arg since V1 is treated as 2nd arg

df %>% select(V1) %>% str_sub(V2, V3) # Here V2 and V3 are not recognized
Run Code Online (Sandbox Code Playgroud)

tal*_*lat 5

您可以执行以下操作:

library(dplyr)
library(stringr)
library(lazyeval)

df %>% mutate(new = str_sub(V1, V2, V3))
#       V1 V2 V3 new
#1 ABBEDHH  4  5  ED
#2   DEFGH  2  2   E
#3    EFGF  1  2  EF
#4    EEFD  1  1   E
Run Code Online (Sandbox Code Playgroud)

请注意,这dplyr是为了使用data.frames,因此输入和输出应该是data.frames,而不是原子向量.