[英]Mark all values given value in dataframe
我有一个带有时间数据的数据框,我想用它来标记某些行属于某个时间段。 例如:
time <- c(1,2,3,5,7,9,23,24,28,43,45)
action <- c("clap","blink","stare","stare","clap","stare",
"clap","blink","stare","clap","stare")
我想找到每个拍子5秒内发生的情况,希望通过创建一个新列来为每个新的拍子和拍手序列提供索引标记。
我是R的新手,因此可能有一种措辞措辞可以帮助寻找答案,因此我很抱歉。
我相信这是您想要的。 请注意,我已经在data.frame
添加了一行,因为您提到要让标识符查看拍手后5秒钟内是否发生了什么。
# Your data
time <- c(1,2,3,5,7,9,23,24,28,43,45)
action <- c("clap","blink","stare","stare","clap","stare",
"clap","blink","stare","clap","stare")
df = data.frame(time=time,action=action)
# Added a row that does not occur within 5 seconds of a clap for illustration purposes.
df = rbind(df,data.frame(time=100,action='stare'))
# Add the group number, based on the claps.
df = df %>% mutate(group=cumsum(action=='clap'))
# Check if action is within 5 seconds of a clap.
df = df %>%
group_by(group) %>%
mutate(within_5_seconds = ifelse(time-time[1]<=5,1,0)) %>%
as.data.table
输出:
time action group within_5_seconds
1: 1 clap 1 1
2: 2 blink 1 1
3: 3 stare 1 1
4: 5 stare 1 1
5: 7 clap 2 1
6: 9 stare 2 1
7: 23 clap 3 1
8: 24 blink 3 1
9: 28 stare 3 1
10: 43 clap 4 1
11: 45 stare 4 1
12: 100 stare 4 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.