如何使用自定义函数将因子应用于更大时间序列的不同子集?

时间:2011-12-22 10:40:03

标签: r

我正在测量许多患者的毫秒时间戳的生理变量。对于每位患者,我想将一个因子应用于描述其在该确切时刻的姿势的时间戳行的子集。

我尝试过创建以下功能,在描述第一个姿势时效果很好。当尝试应用下一个“姿势因素”时,先前注册的姿势将被删除。

TestPatient <- data.frame(Time=seq(c(ISOdatetime(2011,12,22,12,00,00)), by = "sec", length.out = 100),Value=rnorm(100, 9, 3))

patientpositionslice <- function(patient,positiontype,timestart,timestop) {
  patient$Position[
    format(patient$Time, "%Y-%m-%d %H:%M:%S") >= timestart &
    format(patient$Time, "%Y-%m-%d %H:%M:%S") <  timestop] <- positiontype
  patient
}

TestPatientNew <- patientpositionslice(TestPatient,"Horizontal","2011-12-22 12:00:05","2011-12-22 12:00:10")
TestPatientNew <- patientpositionslice(TestPatient,"Vertical","2011-12-22 12:00:15","2011-12-22 12:00:20")

如何修改功能,以便我可以在不同姿势上重复应用它,例如“水平”,“垂直”,“坐着”等?

1 个答案:

答案 0 :(得分:1)

这是您的解决方案。可能有更优雅的方式,但这是我的;)

 TestPatient <- data.frame(Time=seq(c(ISOdatetime(2011,12,22,12,00,00)), by = "sec",   length.out = 100),Value=rnorm(100, 9, 3))
 #Included column with position
 TestPatient$position <- NA

 patientpositionslice <- function(patient,positiontype,timestart,timestop) {
   #changed the test to ifelse() function
   new<-ifelse(
      format(patient$Time, "%Y-%m-%d %H:%M:%S") >= timestart &
      format(patient$Time, "%Y-%m-%d %H:%M:%S") <  timestop , positiontype, patient$position)
 patient$position <- new
 patient
 }

 TestPatientNew <- patientpositionslice(TestPatient,"Horizontal","2011-12-22 12:00:05","2011-12-22 12:00:10")
 #For repeated insertion use the previous object
 TestPatientNew <- patientpositionslice(TestPatientNew ,"Vertical","2011-12-22 12:00:15","2011-12-22 12:00:20")

我评论了这些变化。希望它就像你想要它只是纠正我。