首页 > 解决方案 > 根据 R 中前一行的值更改列中的值

问题描述

我有一个看起来有点像这样的数据集:

Time Event           Value
1     right cue       4
2     right cue       5
3     reaction        6
4     reaction        7
5     reaction        5
6     left cue        7
7     left cue        4
8     reaction        2

我想分别获得左右反应的开始和结束之间的平均值。我的问题是数据只是被标记为“反应”,没有左右。如何根据前一行中的值(左或右提示)将“反应”重命名为“左/右反应”?

标签: rrename

解决方案


这是否有效:

library(dplyr)
library(tidyr)
library(stringr)
df %>% mutate(dir = str_extract(Event, 'right|left')) %>% 
fill(dir, .direction = 'down') %>% 
mutate(Event = case_when(str_detect(Event, 'left|right') ~ Event, 
                         TRUE ~ str_c(dir,Event, sep = ' '))) %>% select(-dir)

# A tibble: 8 x 3
   Time Event          Value
  <dbl> <chr>          <dbl>
1     1 right cue          4
2     2 right cue          5
3     3 right reaction     6
4     4 right reaction     7
5     5 right reaction     5
6     6 left cue           7
7     7 left cue           4
8     8 left reaction      2

推荐阅读