首页 > 解决方案 > 查找多列中的差异并计算更改

问题描述

我正在努力处理一些数据。为了得到下表,我使用了 group_by 和 summarise_at 来查找 Q1-Q10 的均值cidtime(我从每个 cid 和每个时间点的多个值开始),然后过滤到只有大约两个时间出现的 cid 1和2。使用这个(或者如果有更清洁的方法,或者回到我的原始数据)我想计算cid在时间2增加了多少Q1-Q10的平均值,然后,对于每个GROUP头脑的平均数增加。

GROUP  cid   time    Q1    Q2    Q3    Q4    Q5    Q6    Q7    Q8    Q9    Q10
A      169   1       4.45  4.09  3.91  3.73  3.82  4.27  3.55  4     4.55  3.91
A      169   2       4.56  4.15  4.06  3.94  4.09  4.53  3.91  3.97  4.12  4.21
A      184   1       4.64  4.18  3.45  3.64  3.82  4.55  3.91  4.27  4     3.55
A      184   2       3.9   3.6   3     3.6   3.4   3.9   3     3.5   3.2   3.1 
B      277   1       4.43  4.21  3.64  4.36  4.36  4.57  4.36  4.29  4.07  4.07
B      277   2       4.11  4     3.56  3.44  3.67  4     3.89  3.78  3.44  3.89
...

我已经看到使用数据的示例spreadiris但这是针对单个变量的差异。任何帮助表示赞赏。

标签: rdplyr

解决方案


Try this. Gives you the mean increase by GROUP and Qs:

df <- read.table(text = "GROUP  cid   time    Q1    Q2    Q3    Q4    Q5    Q6    Q7    Q8    Q9    Q10
A      169   1       4.45  4.09  3.91  3.73  3.82  4.27  3.55  4     4.55  3.91
A      169   2       4.56  4.15  4.06  3.94  4.09  4.53  3.91  3.97  4.12  4.21
A      184   1       4.64  4.18  3.45  3.64  3.82  4.55  3.91  4.27  4     3.55
A      184   2       3.9   3.6   3     3.6   3.4   3.9   3     3.5   3.2   3.1 
B      277   1       4.43  4.21  3.64  4.36  4.36  4.57  4.36  4.29  4.07  4.07
B      277   2       4.11  4     3.56  3.44  3.67  4     3.89  3.78  3.44  3.89", header = TRUE)

library(dplyr)
library(tidyr)

df %>% 
  # Convert to long
  pivot_longer(-c(GROUP, cid, time), names_to = "Q") %>% 
  # Group by GROUP, cid, Q
  group_by(GROUP, cid, Q) %>%
  # Just in case: sort by time
  arrange(time) %>% 
  # Increased at time 2 using lag
  mutate(is_increase = value > lag(value)) %>% 
  # Mean increase by GROUP and Q 
  group_by(GROUP, Q) %>% 
  summarise(mean_inc = mean(is_increase, na.rm = TRUE))
#> # A tibble: 20 x 3
#> # Groups:   GROUP [2]
#>    GROUP Q     mean_inc
#>    <fct> <chr>    <dbl>
#>  1 A     Q1         0.5
#>  2 A     Q10        0.5
#>  3 A     Q2         0.5
#>  4 A     Q3         0.5
#>  5 A     Q4         0.5
#>  6 A     Q5         0.5
#>  7 A     Q6         0.5
#>  8 A     Q7         0.5
#>  9 A     Q8         0  
#> 10 A     Q9         0  
#> 11 B     Q1         0  
#> 12 B     Q10        0  
#> 13 B     Q2         0  
#> 14 B     Q3         0  
#> 15 B     Q4         0  
#> 16 B     Q5         0  
#> 17 B     Q6         0  
#> 18 B     Q7         0  
#> 19 B     Q8         0  
#> 20 B     Q9         0

Created on 2020-04-12 by the reprex package (v0.3.0)


推荐阅读