当使用pmin和pmax时,dplyr:mutate和transform之间的区别?

Jam*_*mes 9 r dplyr

在试图回答这个问题,我遇到之间的差异mutate,并transform在我的预期是等价的操作.

# data
x <- data.frame(a=c(rep(0,10),rep(1,10),3),b=c(1:10,0,11:19,0))

#transform
transform(x,a=pmin(a,b), b=pmax(a,b))
   a  b
1  0  1
2  0  2
3  0  3
4  0  4
5  0  5
6  0  6
7  0  7
8  0  8
9  0  9
10 0 10
11 0  1
12 1 11
13 1 12
14 1 13
15 1 14
16 1 15
17 1 16
18 1 17
19 1 18
20 1 19
21 0  3

#mutate
libarary(dplyr)
x %>% mutate(a=pmin(a,b), b=pmax(a,b))
   a  b
1  0  1
2  0  2
3  0  3
4  0  4
5  0  5
6  0  6
7  0  7
8  0  8
9  0  9
10 0 10
11 0  0
12 1 11
13 1 12
14 1 13
15 1 14
16 1 15
17 1 16
18 1 17
19 1 18
20 1 19
21 0  0
Run Code Online (Sandbox Code Playgroud)

注意第11行和第21行的差异.我怀疑这mutate是在改变数据,因此,pmax没有看到原始数据.它是否正确?它是一个bug还是设计?

Jam*_*mes 6

看来我的怀疑是正确的,并且设计允许在之后立即使用计算变量,例如:

data.frame(a=1:4,b=5:8) %>% mutate(sum=a+b, letter=letters[sum])
  a b sum letter
1 1 5   6      f
2 2 6   8      h
3 3 7  10      j
4 4 8  12      l
Run Code Online (Sandbox Code Playgroud)

为了从transform一个人那里复制预期的行为,只需直接引用变量:

x %>% mutate(a=pmin(x$a,x$b), b=pmax(x$a,x$b))
   a  b
1  0  1
2  0  2
3  0  3
4  0  4
5  0  5
6  0  6
7  0  7
8  0  8
9  0  9
10 0 10
11 0  1
12 1 11
13 1 12
14 1 13
15 1 14
16 1 15
17 1 16
18 1 17
19 1 18
20 1 19
21 0  3
Run Code Online (Sandbox Code Playgroud)

  • 没有明确关于 `pmin` 和 `pmax`,但您可以在 [dplyr 小插图](http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html) 中阅读有关此行为的信息:`dplyr ::mutate()` 与 `plyr::mutate()` 的工作方式相同,也与 `base::transform()` 类似。`mutate()` 和 `transform()` 之间的主要区别在于 mutate 允许您引用您刚刚创建的列 [示例中的 'a' 列]" (2认同)