在dplyr中复制Base R操作

时间:2019-04-29 00:03:59

标签: r dplyr

我正在尝试使用dplyr复制一组操作,由于某种原因,我的尝试未能获得相同的结果。我的问题有两点:1.为什么我编写的dplyr版本与基本操作的结果不同?2.什么是最清晰的dplyr(管道)实现。首先,这里是一些样本数据,这些数据比我自己的问题小:

abc <- data.frame(a = rnorm(100, 5, 6), b = rnorm(100, 2, 3), c = rnorm(100, 0, 5), d = rnorm(100, 50, 3))
rand <- sample(c(1:100), 100, replace = F)
e <- 5
f <- 50

以下是在基数R中的情况。

# Case 1 
abc.2 <- abc[rand,][(rand <= f) | (abc[rand, "a"] < e),]

这是我尝试使用dplyr的尝试,但是abc.3的结果不同于abc.2

# Case 2

abc.3 <- abc[rand,]
abc.3 <- abc.3 %>% filter(d >= f | d < e)

这是怎么回事?!?

2 个答案:

答案 0 :(得分:3)

您似乎在d解决方案中使用dplyr,但没有在base中使用 并且您使用(abc[rand, "a"] < e)是主要区别,因为在dplyr解决方案中,您只能使用a < e。下面,我刚刚尝试在base r中重新创建您的dplyr解决方案。似乎可行

由于dplyr对数据帧的处理,行ID有所不同

abc <- data.frame(a = rnorm(100, 5, 6), b = rnorm(100, 2, 3), c = rnorm(100, 0, 5), d = rnorm(100, 50, 3))
rand <- sample(c(1:100), 100, replace = F)
e <- 5
f <- 50

abc.2 <- abc[rand,][(rand <= f) | (abc[rand, "a"] < e),]

abc.3 <- abc[rand,]
abc.3 <- abc.3 %>% filter(rand <= f | a < e)


> all.equal(abc.2$a, abc.3$a)
[1] TRUE
> all.equal(abc.2$b, abc.3$b)
[1] TRUE
> all.equal(abc.2$c, abc.3$c)
[1] TRUE
> all.equal(abc.2$d, abc.3$d)
[1] TRUE
> all.equal(abc.2, abc.3)
[1] "Attributes: < Component “row.names”: Mean relative difference: 0.7186996 >"

答案 1 :(得分:2)

我认为dplyr版本将使用slice

library(dplyr)
abc. 3 <- abc %>% slice(rand[(rand <= f) | (a[rand] < e)])

我们可以比较输出

head(abc.2)
#            a          b           c        d
#5   4.1933216 1.89493799   0.1185014 50.17590
#59 -0.8447520 0.02859712  -8.5168739 49.04809
#32 12.9969641 5.17795376  -6.0270349 50.63730
#52 -0.5149191 4.01784805   0.8158744 50.88895
#28  7.4209741 2.71737567  -0.7756451 48.84768
#37 11.9426428 3.67445186 -10.7043711 49.88126

head(abc.3)
#           a          b           c        d
#1  4.1933216 1.89493799   0.1185014 50.17590
#2 -0.8447520 0.02859712  -8.5168739 49.04809
#3 12.9969641 5.17795376  -6.0270349 50.63730
#4 -0.5149191 4.01784805   0.8158744 50.88895
#5  7.4209741 2.71737567  -0.7756451 48.84768
#6 11.9426428 3.67445186 -10.7043711 49.88126

tail(abc.2)
#            a           b          c        d
#43  1.2259801 -0.09873229  3.4330413 54.19566
#10 12.5498938  3.03150006  7.2630499 50.08077
#49 -2.5949440 -1.65535917  7.6826515 46.42876
#80 -0.1063651 -0.81405361 -0.5607432 51.30927
#18  0.8502235  3.22688781 -3.4557019 53.39594
#22  1.8523659  7.89332620 -3.3389127 47.00231

tail(abc.3)
#            a           b          c        d
#73  1.2259801 -0.09873229  3.4330413 54.19566
#74 12.5498938  3.03150006  7.2630499 50.08077
#75 -2.5949440 -1.65535917  7.6826515 46.42876
#76 -0.1063651 -0.81405361 -0.5607432 51.30927
#77  0.8502235  3.22688781 -3.4557019 53.39594
#78  1.8523659  7.89332620 -3.3389127 47.00231