我试图通过将所有变量保留在dplyr
包中的最终数据集中来计算时间平均值。这是我的样本数据集的样子:
library(dplyr)
id <- c(1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4)
gender <- c(1,1,1,1, 2,2,2,2, 2,2,2,2, 1,1,1,1)
item.id <-c(1,1,1,2, 1,1,2,2, 1,2,3,4, 1,2,2,3)
sequence<-c(1,2,3,1, 1,2,1,2, 1,1,1,1, 1,1,2,1)
time <- c(5,6,7,1, 2,3,4,9, 1,2,3,9, 5,6,7,8)
data <- data.frame(id, gender, item.id, sequence, time)
> data
id gender item.id sequence time
1 1 1 1 1 5
2 1 1 1 2 6
3 1 1 1 3 7
4 1 1 2 1 1
5 2 2 1 1 2
6 2 2 1 2 3
7 2 2 2 1 4
8 2 2 2 2 9
9 3 2 1 1 1
10 3 2 2 1 2
11 3 2 3 1 3
12 3 2 4 1 9
13 4 1 1 1 5
14 4 1 2 1 6
15 4 1 2 2 7
16 4 1 3 1 8
id
对于学生证,gender
对于性别,item.id
对于学生要回答的问题ID,sequence
是解决问题的尝试序列号,因为学生可能会回到问题并再次回答,并且time
是每次尝试所花费的时间。
在计算时间平均值时,我需要遵循三个步骤:
(a)
学生对每个问题进行多次试验。我需要为每个具有多次试验的项目计算时间平均值。
(b)
然后计算每个时间的总时间平均值id
。例如,对于id=1
,我有两个项目,第一个项目有3个试验,第二个项目有1个试验。首先,我需要聚集通过的第一个项目的时间(5+6+7)/3=6
,所以id=1
有物品1时间6
和ITEM2时间1
。其次,以6
和1
和计算平均为这个学生(6+1)/2=3.5
。
(c)
最后,我想将所有变量保留在数据集中。
data <- data %>%
group_by(id) %>%
select(id, gender, item.id, sequence, time) %>%
summarize(mean.time = mean(time))
我明白了这一点,但显然,这只是在不考虑每次试验的均值范围内汇总均值,而且也没有保留所有变量:
> data
# A tibble: 4 x 2
id mean.time
<dbl> <dbl>
1 1 4.75
2 2 4.5
3 3 3.75
4 4 6.5
我以为select()
会保留所有变量。
最终数据集应如下所示:
> data
id gender item.id sequence time mean.time
1 1 1 1 1 5 3.5
2 1 1 1 2 6 3.5
3 1 1 1 3 7 3.5
4 1 1 2 1 1 3.5
5 2 2 1 1 2 4.5
6 2 2 1 2 3 4.5
7 2 2 2 1 4 4.5
8 2 2 2 2 5 4.5
9 3 2 1 1 1 3.75
10 3 2 2 1 2 3.75
11 3 2 3 1 3 3.75
12 3 2 4 1 9 3.75
13 4 1 1 1 5 6.5
14 4 1 2 1 6 6.5
15 4 1 2 2 7 6.5
16 4 1 3 1 8 6.5
我使用过dplyr
但打开了其他解决方案。提前致谢!
我们可以使用mutate
而不是summarise
作为summarise
返回值(每组1行)的汇总输出,而mutate
在数据集中创建新列
...
%>%
mutate(mean.time = mean(time))
如果凌晨想要得到mean
的mean
由“身份证”,那么第一组,“item.id”,得到mean
,然后通过“ID”进行分组,得到mean
的unique
元素
data %>%
group_by(id, item.id) %>%
mutate(mean.time = mean(time)) %>%
group_by(id) %>%
mutate(mean.time = mean(unique(mean.time)))
# A tibble: 16 x 6
# Groups: id [4]
# id gender item.id sequence time mean.time
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1 1 1 1 5 3.5
# 2 1 1 1 2 6 3.5
# 3 1 1 1 3 7 3.5
# 4 1 1 2 1 1 3.5
# 5 2 2 1 1 2 4.5
# 6 2 2 1 2 3 4.5
# 7 2 2 2 1 4 4.5
# 8 2 2 2 2 9 4.5
# 9 3 2 1 1 1 3.75
#10 3 2 2 1 2 3.75
#11 3 2 3 1 3 3.75
#12 3 2 4 1 9 3.75
#13 4 1 1 1 5 6.5
#14 4 1 2 1 6 6.5
#15 4 1 2 2 7 6.5
#16 4 1 3 1 8 6.5
或代替创建第二个分组,我们可以执行一个操作match
以获取“ item.id”的第一个位置,提取“ mean.time”并获取mean
data %>%
group_by(id, item.id) %>%
mutate(mean.time = mean(time),
mean.time = mean(mean.time[match(unique(item.id), item.id)]))
或使用summarise
然后做一个left_join
data %>%
group_by(id, item.id) %>%
summarise(mean.time = mean(time)) %>%
group_by(id) %>%
summarise(mean.time = mean(mean.time)) %>%
right_join(data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句