在R中的数据帧中每三次计算连续值

时间:2017-06-21 16:16:40

标签: r dataframe time-series counter

我有这个

this.appservice.newCompInit(this.componentName)

我需要计算t3,t6和t9中每行的“1”。 每次计数器达到3必须回到零并重新开始。

在这种情况下,结果应为:

df<-cbind(
t1=c(1,1,1),
t2=c(1,1,1),
t3=c(0,1,1),
t4=c(1,0,1),
t5=c(1,1,1),
t6=c(1,1,1),
t7=c(1,1,0),
t8=c(0,1,1),
t9=c(1,1,1))


> df
     t1 t2 t3 t4 t5 t6 t7 t8 t9
[1,]  1  1  0  1  1  1  1  0  1
[2,]  1  1  1  0  1  1  1  1  1
[3,]  1  1  1  1  1  1  0  1  1

如何在t3,t6和t9计算这些连续的“1”值? 我看过但是我还是遇到了麻烦!

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:1)

这样的东西可以工作(编辑以修复以0结尾的计数):

dat <- as.data.frame(df)
new_t3 <- c()
for(i in 1:3){
    if(dat[i,3] != 0){
        count <- rle(dat[i,1:3])
        new_t3 <- append(new_t3, count$length[count$values == 1])
    } else{
        new_t3 <- append(new_t3, 0)
    }
}

这会将列t1的每一行循环到t3,并使用rle函数计算连续值的数量。 count$length[count$values == 1]访问rle返回的对象中值等于1的连续计数。您必须为您计算的每个列组执行此操作,例如:

new_t6 <- c()
for(i in 1:3){
    if(dat[i,6] != 0){
        count <- rle(dat[i,4:6])
        new_t6 <- append(new_t6, count$length[count$values == 1])
    } else{
        new_t6 <- append(new_t6, 0)
    }
}

或以某种方式将循环包装在函数或嵌套for循环中以自动化表。但它看起来像返回示例中的值。请注意,对于new_t9,此方法会返回1 1 3 2,因为第一行中有两个单1个值(1 0 1)。如果您需要避免使用此类型的结果(可能使用countunique),您可能需要对max变量执行某些操作。

df更改为允许rle工作的数据框对象,否则无法访问这些值。

答案 1 :(得分:1)

这里有一个可能的方法,使用一个好的旧for循环结合apply:

aggregateRow <- function(row){
  result <- rep(NA,length(row) %/% 3)
  cumul <- 0
  for(i in 1:length(row)){
    cumul <- cumul + row[i]
    if(i %% 3 == 0){
      if(row[i] == 0)
        cumul = 0
      if(cumul > 3)
        cumul = cumul - 3
      result[i %/% 3] = cumul
    }
  }
  return(result)
}

res <- t(apply(df,1,aggregateRow))
row.names(res) <- paste0('new_t',c(3,6,9)) # just to give names to the rows
> res
       [,1] [,2] [,3]
new_t3    0    3    2
new_t6    3    2    2
new_t9    3    3    2