Identification of TRUE blocks in the list

I am analyzing and using R. I ran into a problem:

I have a list of logics that looks like this:

list = (TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE)

for each logical value a there is a list of numerical values:

num = (1, 4, 3, 7, 3, 2 , 23, 98, 5)

I would like to summarize the values โ€‹โ€‹for TRUE blocks and put them in a matrix or sth.

Just:

list[1] == TRUE and list[2] == TRUE and list[3] == TRUE, so I calculate the sum: 1 + 4 + 3 = 8 therefore matrix[1,1] <- 8, and then omit the list [4] and list [5], because it is FALSE and go to list [6], matrix[2,1] <- 2... and so on ...

I do not know how to extract these TRUE blocks. I hope you can help me somehow!

+4
source share
2 answers

rle - :

myL = c(TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE)
num = c(1, 4, 3, 7, 3, 2 , 23, 98, 5)
X <- rle(myL)
Y <- rep(seq_along(X$lengths)[X$values], X$lengths[X$values])
tapply(num[myL], Y, sum)
  1   3   5 
  8   2 103 

TRUE 8, ( ) 2, (98 5) 103.


, "SOfun" GitHub, TrueSeq, .

:

library(devtools)
install_github("mrdwab/SOfun")

:

TrueSeq(myL)
# [1] 1 1 1 0 0 2 0 3 3

:

tapply(num, TrueSeq(myL), sum)
#   0   1   2   3 
#  33   8   2 103 

, , zero2NA TrueSeq, :

tapply(num, TrueSeq(myL, zero2NA=TRUE), sum)
#   1   2   3 
#   8   2 103
+4

, diff :

vec = c(TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE)
c(vec[1]==TRUE,diff(vec))
## [1]  1  0  0 -1  0  1 -1  1  0

, 1, , 0. -1 , .

+1

Source: https://habr.com/ru/post/1548033/


All Articles