r - 在由另一列分组的一列中添加取值差异的列
问题描述
我有一个名为 diff_colour_valid_int1 的 df:
> head(diff_colour_valid_int1)
# A tibble: 6 x 5
# Groups: search_difficulty, cue_validity [3]
search_difficulty cue_validity cue_colour meanrt stdev
<fct> <fct> <fct> <dbl> <dbl>
1 difficult FALSE Match (Color) cue 0.990 0.158
2 difficult FALSE Mismatch (Onset) cue 0.972 0.150
3 difficult TRUE Match (Color) cue 0.828 0.133
4 difficult TRUE Mismatch (Onset) cue 0.881 0.177
5 easy FALSE Match (Color) cue 0.813 0.132
6 easy FALSE Mismatch (Onset) cue 0.801 0.137
>
我想添加一个名为 cue_effect 的列,它计算每个 cue_validity 对(例如前两个 FALSE FALSE)的 meanrt 值之间的差异。因此,该列的前六个值将是:
cue_effect
<dbl>
0.018
0.018
-0.053
-0.053
0.012
任何建议表示赞赏。谢谢。
解决方案
我们可以使用rleid
创建分组列
library(dplyr)
library(data.table)
diff_colour_valid_int1 %>%
group_by(search_difficulty, grp = rleid(cue_validity)) %>%
mutate(cue_effect = -diff(meanrt))
-输出
# A tibble: 6 x 7
# Groups: search_difficulty, grp [3]
# search_difficulty cue_validity cue_colour meanrt stdev grp cue_effect
# <chr> <lgl> <chr> <dbl> <dbl> <int> <dbl>
#1 difficult FALSE Match (Color) cue 0.99 0.158 1 0.018
#2 difficult FALSE Mismatch (Onset) cue 0.972 0.15 1 0.018
#3 difficult TRUE Match (Color) cue 0.828 0.133 2 -0.053
#4 difficult TRUE Mismatch (Onset) cue 0.881 0.177 2 -0.053
#5 easy FALSE Match (Color) cue 0.813 0.132 3 0.0120
#6 easy FALSE Mismatch (Onset) cue 0.801 0.137 3 0.0120
数据
diff_colour_valid_int1 <- structure(list(search_difficulty = c("difficult", "difficult",
"difficult", "difficult", "easy", "easy"), cue_validity = c(FALSE,
FALSE, TRUE, TRUE, FALSE, FALSE), cue_colour = c("Match (Color) cue",
"Mismatch (Onset) cue", "Match (Color) cue", "Mismatch (Onset) cue",
"Match (Color) cue", "Mismatch (Onset) cue"), meanrt = c(0.99,
0.972, 0.828, 0.881, 0.813, 0.801), stdev = c(0.158, 0.15, 0.133,
0.177, 0.132, 0.137)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
推荐阅读
- java - 如何使用jsoup从div中的2中选择1个跨度
- ag-grid-react - 树模式下的 AG-Grid 页脚未更新
- python - Python:是否有类似 matlab 的反斜杠运算符?
- entity-framework - 如何创建 Group By LINQ 查询
- tensorflow - LSTM 的梯度一对多模型输出 wrt 输入
- java - spring AnnotationUtils in 5.2 不再搜索父类?
- ruby-on-rails - HelpScout Mailbox API 2.0 - 如何创建从“用户”到“客户”的传出对话
- c# - Gmail uses its sending account address as the reply-to, rather than person filling out the inquiry form
- c - Why is my pointer array returning a character in unicode?
- python-3.x - Python3. How to optimize decorator for handling exceptions?