如何识别一列中几行上的模式,并使用R向新列填充有关该模式的信息? [英] How can I identify patterns over several rows in a column and fill a new column with information about that pattern using R?

查看:14
本文介绍了如何识别一列中几行上的模式,并使用R向新列填充有关该模式的信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个数据集,其中我有一个虚拟变量,它告诉我参与者何时靠近椅子,何时离开椅子。我为每个参与者都有一个ID,当参与者靠近椅子时,Dummy=1,当他们离椅子很远时,Dummy=0。数据大约每30秒更新一次(它的时间不是很准确,所以我不能使用这些信息来帮助识别模式)。如果参与者在椅子上停留2分钟,那么我们将有4个观察,其中D=1。使用虚拟变量,我想确定参与者从椅子上移开然后再向椅子移动的起点。我还希望使用变量(或类似TRUE当它符合该模式时或离开、漫游和回来时)来填充列。

注意:整个活动可能以个人离开椅子或靠近椅子而结束。

df1展示了我正在使用的数据帧的示例,df2是最终的数据帧。我假设我必须使用正则表达式或grep来获得最终输出,但我对这两种方法都不是特别熟悉,我可以使用一些指导!

df1

TIME        ID        D
12:30:10    2         0
12:30:42    2         0
12:30:59    2         1
12:31:20    2         0
12:31:50    2         0
12:32:11    2         0
12:32:45    2         1
12:33:10    2         1
12:33:33    2         1
12:33:55    2         1
12:34:15    2         0
12:34:30    2         0

我最后想要的是:

df2

TIME        ID        D      Pattern
12:30:10    2         0      FALSE
12:30:42    2         0      FALSE
12:30:59    2         1      TRUE
12:31:20    2         0      TRUE     
12:31:50    2         0      TRUE
12:32:11    2         0      TRUE
12:32:45    2         1      TRUE
12:33:10    2         1      FALSE
12:33:33    2         1      FALSE
12:33:55    2         1      FALSE
12:34:15    2         0      FALSE
12:34:30    2         0      FALSE

最终,我希望得到一个数据框,其中的观测值仅包括为真的行。

同样,数据帧包括几个ID和类似的事件。

谢谢!

推荐答案

这里有一个data.table方法...

样本数据

library( data.table )
DT <- fread("TIME        ID        D
12:30:10    2         0
12:30:42    2         0
12:30:59    2         1
12:31:20    2         0
12:31:50    2         0
12:32:11    2         0
12:32:45    2         1
12:33:10    2         1
12:33:33    2         1
12:33:55    2         1
12:34:15    2         0
12:34:30    2         0")
#you can also use data.table::setDT( mydata ) to make mydata
#  a data.table. If so, make sure to replace DT below with mydata.

代码

#create a list with strings of all D's by ID
temp <- DT[, .( D = paste0( D, collapse = "" ) ), by = .(ID) ]
#build a named replace vector, base on the 1[0]+1-pattern
replace_vector <- gsub( ".", "A", unlist( stringr::str_extract_all( temp$D, "1[0]+1" ) ) )
names( replace_vector ) <- unlist( stringr::str_extract_all( temp$D, "1[0]+1" ) )
#and replace the parts we want to keep with A's
temp[, D2 := stringr::str_replace_all( D, replace_vector )]
#paste pack to original DT
DT[, keep := temp[, strsplit( D2, ""), by = .(ID) ]$V1 ]
#now filter what you want to keep, and drop the keep column
DT[keep == "A", ][, keep := NULL][]

输出

#        TIME ID D
# 1: 12:30:59  2 1
# 2: 12:31:20  2 0
# 3: 12:31:50  2 0
# 4: 12:32:11  2 0
# 5: 12:32:45  2 1     

这篇关于如何识别一列中几行上的模式,并使用R向新列填充有关该模式的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆