r - 查找多列中的差异并计算更改
问题描述
我正在努力处理一些数据。为了得到下表,我使用了 group_by 和 summarise_at 来查找 Q1-Q10 的均值cid
和time
(我从每个 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
...
我已经看到使用数据的示例spread
,iris
但这是针对单个变量的差异。任何帮助表示赞赏。
解决方案
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)
推荐阅读
- html - 如何在后台以重复模式设置图像
- php - 如果php仍在处理,php-fpm nginx magento2用户无法查看另一个页面
- c++ - 子集总和,带有回溯和类
- python - 从系统托盘恢复后,Tkinter 窗口挂起(使用 pystray)
- c# - 我可以为两个现有模型创建一个基础模型吗
- python - 奇异值分解改变结果
- windows - 使用带有 git 指令的特定 ssh 密钥
- css - css nth-child first n 选择器不适用于悬停状态
- python - Python:通过 DOI 请求从 ScienceDirect 下载论文
- ansible - 从匹配条件的ansible中的字典列表中过滤元素