英文:
Subtracting values from specific rows based on groupings in other columns
问题
我有一个数据框:
example <- data.frame(
Subject = c(101,101,101,101,101,101,
102,102,102),
Event = c('Negative_other_6',
'Negative_other_6',
'Negative_self_1',
'Negative_other_6',
'Negative_self_1',
'Negative_self_1',
'Negative_other_5',
'Negative_other_5',
'Negative_other_5'
),
TrialType = c("ReframeNeg", "ImmerseNeu", "ImmerseNeu",
"ImmerseNeg", "ReframeNeg", "ImmerseNeg",
"ReframeNeg", "ImmerseNeu", "ImmerseNeg"),
Rating = c(3,1,1,4,3,5,3,1,5)
)
对于每个相同的事件,我想要从ReframeNeg
的评分中减去ImmerseNeg
的评分。输出应该是一个新的数据框,按Subject
和Event
组织。这应该是示例输出:
solution <- data.frame(
Subject = c(101,101, 102),
Event = c('Negative_other_6',
'Negative_self_1',
'Negative_other_5'),
NegAffDiff = c(1, 2, 2)
)
有人知道我怎么才能实现这个吗?非常感谢!
英文:
I have a dataframe:
example <- data.frame(
Subject = c(101,101,101,101,101,101,
102,102,102),
Event = c('Negative_other_6',
'Negative_other_6',
'Negative_self_1',
'Negative_other_6',
'Negative_self_1',
'Negative_self_1',
'Negative_other_5',
'Negative_other_5',
'Negative_other_5'
),
TrialType = c("ReframeNeg", "ImmerseNeu", "ImmerseNeu",
"ImmerseNeg", "ReframeNeg", "ImmerseNeg",
"ReframeNeg", "ImmerseNeu", "ImmerseNeg"),
Rating = c(3,1,1,4,3,5,3,1,5)
)
For each of the same event, I want to subtract the rating ReframeNeg
from ImmerseNeg
. The output should be a new dataframe that's organized by Subject
and Event
. This should be the example output:
solution <- data.frame(
Subject = c(101,101, 102),
Event = c('Negative_other_6',
'Negative_self_1',
'Negative_other_5'),
NegAffDiff = c(1, 2, 2)
)
Does anyone know how I can achieve this? Thanks so much!
答案1
得分: 0
以下是使用您的示例数据的一种选项。您可以使用pivot_wider来为每个TrialType创建一个列,为每个Subject/Event/TrialType组合分配Rating。然后找到ReframeNeg和ImmerseNeg之间的差异。
library(dplyr)
library(tidyr)
example %>%
pivot_wider(names_from = c("TrialType"), values_from = "Rating") %>%
mutate(NegAffDiff = ImmerseNeg - ReframeNeg) %>%
select(Subject, Event, NegAffDiff)
一个数据表: 3 × 3
Subject Event NegAffDiff
1 101 Negative_other_6 1
2 101 Negative_self_1 2
3 102 Negative_other_5 2
<details>
<summary>英文:</summary>
Here's one option using your sample data. You can use pivot wider to create a column for each TrialType which assigns the Rating for each combo of Subject/Event/TrialType. Then find the difference between ReframeNeg and ImmerseNeg.
library(dplyr)
library(tidyr)
example %>%
pivot_wider(names_from = c("TrialType"), values_from = "Rating") %>%
mutate(NegAffDiff = ImmerseNeg - ReframeNeg) %>%
select(Subject, Event, NegAffDiff)
A tibble: 3 × 3
Subject Event NegAffDiff
<dbl> <fct> <dbl>
1 101 Negative_other_6 1
2 101 Negative_self_1 2
3 102 Negative_other_5 2
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论