英文:
Averaging across specific trials with some overlapping labels
问题
这是你要翻译的部分:
我有一个数据框,可以简化如下:
example <- data.frame(
Subject = c(101,101,101,101,101,101,
102,102),
`Event Full` = c('SocReframeNeg',
'SocReframeNeg',
'SelfReframeNeg',
'SelfReframeNeg',
'SocReframeNeg',
'SocReframeNeg',
'SocImmerseNeg',
'SocImmerseNeg'),
Score = c(2,3,3,4,5,6,7,8)
)
我想找到每个受试者每次试验的平均值,并对'unique'试验进行编号。请注意,在同一受试者内可能有多种相同标签的试验(例如,对于受试者101的SocReframeNeg),我不想对它们进行平均。我只想对在`Event Full`中具有该标签的所有行进行平均,直到下一行的值变为另一个值(例如,当`Event Full`从SocReframeNeg切换到SelfReframeNeg时)。
这是期望的输出:
solution <- data.frame(
Subject = c(101, 101, 101, 102),
Num = c(1,2,3,1),
`Event Full` = c("SocReframeNeg", "SelfReframeNeg", 'SocReframeNeg', 'SocImmerseNeg'),
Score = c(2.5,3.5,5.5,7.5)
)
有人知道如何做到这一点吗?
谢谢!
英文:
I have a dataframe that can be simplified like this:
example <- data.frame(
Subject = c(101,101,101,101,101,101,
102,102),
`Event Full` = c('SocReframeNeg',
'SocReframeNeg',
'SelfReframeNeg',
'SelfReframeNeg',
'SocReframeNeg',
'SocReframeNeg',
'SocImmerseNeg',
'SocImmerseNeg'),
Score = c(2,3,3,4,5,6,7,8)
)
I want to find the average value of each trial within each subject and number each 'unique' trial. Note that there are multiple types of trial with the same label within a subject (e.g. SocReframeNeg for subject 101) and I do not want to average across all of them. I only want to average across all the rows with that label in Event Full
until the next row becomes another value (e.g. when Event Full
switches from SocReframeNeg to SelfReframeNeg for subject 101).
This is the desired output:
solution <- data.frame(
Subject = c(101, 101, 101, 102),
Num = c(1,2,3,1),
`Event Full` = c("SocReframeNeg", "SelfReframeNeg", 'SocReframeNeg', 'SocImmerseNeg'),
Score = c(2.5,3.5,5.5,7.5)
)
Does anyone know how to do this?
Thank you!
答案1
得分: 0
library(dplyr)
example |>
mutate(Num = consecutive_id(Event.Full), .by = Subject) |>
summarize(Score = mean(Score), .by = c(Subject, Event.Full, Num))
# Subject Event.Full Num Score
# 1 101 SocReframeNeg 1 2.5
# 2 101 SelfReframeNeg 2 3.5
# 3 101 SocReframeNeg 3 5.5
# 4 102 SocImmerseNeg 1 7.5
英文:
library(dplyr)
example |>
mutate(Num = consecutive_id(Event.Full), .by = Subject) |>
summarize(Score = mean(Score), .by = c(Subject, Event.Full, Num))
# Subject Event.Full Num Score
# 1 101 SocReframeNeg 1 2.5
# 2 101 SelfReframeNeg 2 3.5
# 3 101 SocReframeNeg 3 5.5
# 4 102 SocImmerseNeg 1 7.5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论