在整洁数据中采用一对多组之间的区别

时间:2017-02-21 20:22:17

标签: r tidyr tidyverse

我有一个与Introducing tidyr blog post中的听力率示例类似的整洁数据集,但我在药物下面还有一个“安慰剂”组,我可以像这样构建

with

假设我从整洁的数据开始,我的目标是创建一个名为“diff.p”的新变量,这是每种药物和安慰剂的观察结果之间的差异。结果应如下所示

library(dplyr)
library(tidyr)
messy <- data.frame(
  name = c("Wilbur", "Petunia", "Gregory"),
  a = c(67, 80, 64),
  b = c(56, 90, 50),
  p = c(60, 70, 60)    # this is the new 'placebo' drug
)
tidy <- messy %>% 
        gather(drug, heartrate, a:p)

似乎tidy$diff.p <- c(7,10,4,-4,20,-10,0,0,0) tidy 和/或ave可能是解决方案的良好途径(或者可能构建新的数据框?),但我需要一些关于最佳实践的额外指导。

3 个答案:

答案 0 :(得分:2)

似乎您可以使用第二个tidy

轻松完成此操作
tidy2 <- messy %>%
  mutate(a = a-p, b = b-p, p = 0) %>%
  gather(drug, diff.p, a:p)

left_join(tidy, tidy2, by = c("name", "drug"))
#      name drug heartrate diff.p
# 1  Wilbur    a        67      7
# 2 Petunia    a        80     10
# 3 Gregory    a        64      4
# 4  Wilbur    b        56     -4
# 5 Petunia    b        90     20
# 6 Gregory    b        50    -10
# 7  Wilbur    p        60      0
# 8 Petunia    p        70      0
# 9 Gregory    p        60      0

答案 1 :(得分:2)

dplyr链中,您可以按name分组然后从heartrate[drug=="p"]减去heartrate来执行此操作:

tidy = tidy %>% group_by(name) %>% 
  mutate(diff.p2 = heartrate - heartrate[drug=="p"])
     name  drug heartrate diff.p diff.p2
   <fctr> <chr>     <dbl>  <dbl>   <dbl>
1  Wilbur     a        67      7       7
2 Petunia     a        80     10      10
3 Gregory     a        64      4       4
4  Wilbur     b        56     -4      -4
5 Petunia     b        90     20      20
6 Gregory     b        50    -10     -10
7  Wilbur     p        60      0       0
8 Petunia     p        70      0       0
9 Gregory     p        60      0       0

答案 2 :(得分:0)

另一个选项是data.table

library(data.table)
melt(setDT(messy), id.var = "name", variable.name = "drug", 
 value.name = "heartrate")[, diff.p2 := heartrate - heartrate[drug=="p"]][]
#      name drug heartrate diff.p2
#1:  Wilbur    a        67       7
#2: Petunia    a        80      10
#3: Gregory    a        64       4
#4:  Wilbur    b        56      -4
#5: Petunia    b        90      20
#6: Gregory    b        50     -10
#7:  Wilbur    p        60       0
#8: Petunia    p        70       0
#9: Gregory    p        60       0