2017-06-21 22 views
0

我有此计数连续值三次,每次在一个数据帧中的R

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。 每次计数器到达3必须回零并重新开始。

在这种情况下的结果应该是:

new_t3 = 0, 3, 3 

new_t6 = 3, 2, 3 

new_t9= 1, 3, 2 

我怎么能指望这些连续的“个位”的值在T3,T6和T9? 我看过rle,但我仍然遇到麻烦!

任何帮助:)感谢

+3

为什么new_t3的第一个值是0,而不是2?是不是在t3之前有两个'1'?或者我没有得到什么? – digEmAll

+0

此外,你想每3个元素重置为零,或者只有当总和达到3时才重置为零?请给出你的算法的更多细节......目前你的预期结果似乎是错误的根据你的解释...可能一步一步解释第一行可能就足够了 – digEmAll

+0

弗雷德我无法理解你的结果链接。 – Balter

回答

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) 
    } 
} 

这遍历每个行的列t1t3和用途用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)。如果您需要避免该类型的结果(可能使用uniquemax),则可能必须对count变量执行一些操作。

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

+0

我不明白为什么在new_t3你得到** 2,3,3 **,那个柜台在t3应该是空的。另外,我明白new_t9的重点,我只会在df中选择正确的1。非常感谢! –

+0

new_t3是2,3,3,因为在第一行中有两个连续的1(然后在第2行和第3行中有3和3)。从其他人的看法看来,其他人也期待2,3,3 - 你是不是将第一排中的两个连续1排除在外? – Bird

+0

是的,我不能计算0之前的1,因为在t3的第一行中计数器是空的。 t9的不同故事。我知道有点困惑(t3,t6和t9是我计数的时代)。 –

1

下面是一个使用好老for循环地结合在一起,可能的方法适用于:

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 
+0

Brillant !! ...但是在new_t3(考虑从t7到t9的数据)结果应该是1,3,2。每行中的计数器达到3时停止计数并得到最大值3,当找到从零开始。也许我没有很好地解释这个过程。任何方式都非常感谢! –

相关问题