r - 根据 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
我想分别获得左右反应的开始和结束之间的平均值。我的问题是数据只是被标记为“反应”,没有左右。如何根据前一行中的值(左或右提示)将“反应”重命名为“左/右反应”?
解决方案
这是否有效:
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
推荐阅读
- google-sheets - 特定数据的总数
- python - 如何使用python计算数据框中特定行值之间的时间差?
- node.js - Node-config:如何从配置中获取未冻结的数据?
- react-native - Webview 在 React native (expo) 中不显示任何内容
- c++ - 按另一个向量对向量进行排序
- microsoft-graph-api - 更新和删除日历事件而不向与会者发送通知
- reactjs - 在单选按钮上使用 useState 挂钩的正确方法
- sql-server - 使用来自 SQL UPDATE 查询的多个数据
- typo3 - TYPO3 8.7 自定义内容元素的后端字段未呈现
- azure - Azure 中单个自动化帐户的非工作时间多个启动/停止 VM 解决方案