来自sapply的子结果

时间:2014-11-03 09:05:18

标签: r sapply

在我使用sapply后,我得到一个列表,我想访问这些列表的各个元素。到目前为止,我有:

large.list <- sapply(1:length(visit_num), function(x)  
    seq(enter.shift.want[x], to= exit.prime[x], by= 'hour'))

其中enter.shift.want和exit.prime是日期的向量。

head(large.list, 2)
[[1]]
 [1] "1982-05-17 13:00:00 PDT" "1982-05-17 14:00:00 PDT" "1982-05-17 15:00:00 PDT"
 [4] "1982-05-17 16:00:00 PDT" "1982-05-17 17:00:00 PDT" "1982-05-17 18:00:00 PDT"
 [7] "1982-05-17 19:00:00 PDT" "1982-05-17 20:00:00 PDT" "1982-05-17 21:00:00 PDT"
[10] "1982-05-17 22:00:00 PDT"

[[2]]
 [1] "1982-07-14 13:00:00 PDT" "1982-07-14 14:00:00 PDT" "1982-07-14 15:00:00 PDT"
 [4] "1982-07-14 16:00:00 PDT" "1982-07-14 17:00:00 PDT" "1982-07-14 18:00:00 PDT"
 [7] "1982-07-14 19:00:00 PDT" "1982-07-14 20:00:00 PDT" "1982-07-14 21:00:00 PDT"
[10] "1982-07-14 22:00:00 PDT"

我想将large.list [1]作为日期/时间的向量。 然后我想做

large.list[1]<=enter.shift.want[1] 

并获得真假结果的向量。然后我想要概括和做  对large.list[n]<= enter.shift.want[n]中的每个n (1:length(visit_num)),并加上真/假。

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果enter.shift.wantlistvector,其元素数量与large.list相同,则以下是将其应用于整个list的一种方法

 res <- Map(`<=`, large.list, enter.shift.want)
 res1 <- Map(`<=`, large.list, enter.shift.want1) 

获取每个列表元素TRUE的总数

 colSums(do.call(cbind, res))
 #[1] 3 3

或者

 sapply(res, sum)
 #[1] 3 3

 sapply(res1,sum)
 #[1] 3 7

数据

 large.list <- list(structure(c(390488400, 390492000, 390495600, 390499200, 
 390502800, 390506400, 390510000, 390513600, 390517200, 390520800
 ), class = c("POSIXct", "POSIXt"), tzone = "PDT"), structure(c(395499600, 
 395503200, 395506800, 395510400, 395514000, 395517600, 395521200, 
 395524800, 395528400, 395532000), class = c("POSIXct", "POSIXt"
 ), tzone = "PDT"))


 v1 <- c('1982-05-17 00:00:00', '1982-07-14 00:00:00')
 enter.shift.want <- lapply(v1, function(x) seq(as.POSIXct(x, tz='PDT'),
          length.out=10, by='3 hour'))

 enter.shift.want1 <- as.POSIXct(c('1982-05-17 15:00:00', 
                     '1982-07-14 19:00:00'), tz='PDT')