Loop through dataframe in R and measure time difference between two values

前端 未结 2 1706
囚心锁ツ
囚心锁ツ 2021-01-27 12:12

Summary: I am analyzing the time difference between an occured stimuli (A&B) and a possible response of the user.

The dataset has the following stru

2条回答
  •  梦如初夏
    2021-01-27 12:54

    SQL syntax should be able to get you your answer and is the conventional method for querying tabular data like these. The Data.Table package makes this sort of syntax accessible.

    #import necessary library
    library(data.table)
    
    #instantiate data table
    dt<-data.table(dt)
    
    #convert date field to Date type
    dt$Date <- as.POSIXct(dt$Date, format="%d.%m.%Y %H:%M")
    #create another date field so as not to lose during join
    dt$rollDate<-dt$Date
    
    #create table with stimuliA and set key for sorting/joining purposes
    stima.dt <- dt[StimuliA==1,.(User,rollDate,Date,Hour,StimuliA)]
    setkey(stima.dt,User,rollDate)
    
    #Same for stimuliB
    stimb.dt <- dt[StimuliB==1,.(User,rollDate,Date,Hour,StimuliB)]
    setkey(stimb.dt,User,rollDate)
    
    #same for responses table
    resp.dt <- dt[Responses==1,.(User,rollDate,Date,Hour,Responses)]
    setkey(resp.dt,User,rollDate)
    
    #Join stimuli A table to closes responses
    stim.a<-resp.dt[stima.dt,roll=-Inf]
    
    #calculate Hour differences
    stim.a[,difftime(Date,i.Date,units="min")]
    
    #Join stimuli B table to closes responses
    stim.b<-resp.dt[stimb.dt,roll=-Inf]
    
    #calculate Hour differences
    stim.b[,difftime(Date,i.Date,units="min")]
    

提交回复
热议问题