如何为" lapply"创建多个规则功能

时间:2014-10-21 08:42:09

标签: r lapply

目前,我有一个列表(groupA)数组,如下例所示:

$AAAAAA
       time  timegap
1  06:00:00        0
2  07:00:00       60
3  08:00:00       40
4  09:00:00        0
5  10:00:00       30

$BBBBBBB
       time  timegap
1  06:00:00        0
2  07:00:00       60
3  08:00:00       40
4  09:00:00        0
5  10:00:00       30

我正在尝试创建一个函数,如果timegap大于某个数字,则生成一个虚拟变量。但挑战是如果时间在07:00:00到09:00:00之间,生成虚拟变量的数量将与其他变量不同。

我做的如下:

dummytime<-function(x){
  if(x$time>times("07:00:00") & x$time<times("09:00:00")){
    d<-c(1200) 
  }
  else{
    d<-c(600) 
  }
  dummytime<- as.numeric(x$timegap>=d)
  as.data.frame(dummytime)
}

dumtime<-lapply(groupm2,dummytime)

但是,我收到了这样的错误:

Error in if (as.logical(x$time > times("07:00:00") & x$time < times("09:00:00")))
{ : missing value where TRUE/FALSE needed   

有什么建议吗?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是一种方法。由于您使用chron包将字符转换为时间。我做到了。然后,我创建了一个列表。然后,lpply

library(chron)

# time to Class 'times' 
df1$time <- chron(times = df1$time)
df2$time <- chron(times = df2$time)

# Create a list
ana <- list(df1 = df1, df2 = df2)

#$df1
#      time timegap
#1 06:00:00       0
#2 07:00:00      60
#3 08:00:00      40
#4 09:00:00       0
#5 10:00:00      30

lapply(ana, function(x){
                x$test <- ifelse(x$time >= "07:00:00" & x$time <= "09:00:00",
                1200, 600)
                x

    })

#$df1
#      time timegap test
#1 06:00:00       0  600
#2 07:00:00      60 1200
#3 08:00:00      40 1200
#4 09:00:00       0 1200
#5 10:00:00      30  600

#$df2
#      time timegap test
#1 06:00:00       0  600
#2 07:00:00      60 1200
#3 08:00:00      40 1200
#4 09:00:00       0 1200
#5 10:00:00      30  600

或者

lapply(ana, transform,
       test = ifelse(time >= "07:00:00" & time <= "09:00:00", 1200, 600))