3

下面的问题可以看成是“两列reshape to wide”,有几种方法可以用经典的方式解决,从base::reshape(恐怖)到reshape2. 对于两组情况,简单的子组连接效果最好。

我可以重新制定管道框架内的连接dplyr吗?下面的例子有点傻,但我需要加入更长的管道链,我不想破坏它。

library(dplyr)
d = data.frame(subject= rep(1:5,each=2),treatment=letters[1:2],bp = rnorm(10))

d %>%
  # Assume piped manipulations here
  # Make wide
  # Assume additional piped manipulations here

# Make wide (old style)
with(d,left_join(d[treatment=="a",],
          d[treatment=="b",],by="subject" ))
4

2 回答 2

5

怎么样

d %>% 
  filter(treatment == "a") %>%
  left_join(., filter(d, treatment == "b"), by = "subject")

#  subject treatment.x       bp.x treatment.y      bp.y
#1       1           a  0.4392647           b 0.6741559
#2       2           a -0.6010311           b 1.9845774
#3       3           a  0.1749082           b 1.7678771
#4       4           a -0.3089731           b 0.4427471
#5       5           a -0.8346091           b 1.7156319

您可以在左连接后立即继续管道。

或者,如果您不需要单独的处理列,则可以使用 tidyr 执行以下操作:

library(tidyr)
d %>% spread(treatment, bp)
#  subject          a         b
#1       1  0.4392647 0.6741559
#2       2 -0.6010311 1.9845774
#3       3  0.1749082 1.7678771
#4       4 -0.3089731 0.4427471
#5       5 -0.8346091 1.7156319

(这与Henrik 在评论中指出的使用d %>% dcast(subject ~ treatment, value.var = "bp")from package 相同)reshape2

于 2014-12-11T09:12:18.710 回答
2

使用 group_by 而不是 join 的解决方案。

d %>% 
group_by(subject) %>% 
summarize(bp_a = bp[match("a",treatment)], 
          bp_b = bp[match("b",treatment)])
于 2014-12-13T22:30:50.887 回答