subset - Subsetting data conditional on first instance in R -


data:

row b   1  1 1  2  1 1  3  1 2  4  1 3  5  1 1  6  1 2  7  1 3 

hi all! i'm trying (example above) sum values in column a, when column b = 1 (so starting simple subset line - below).

sum(data$a[data$b==1]) 

however, want first time condition occurs until values switch. if condition re-occurs later in column (row 5 in example), i'm not interested in it!

i'd appreciate in (i suspect simple) problem!

using data.table syntax elegance, can use rle done

library(data.table) dt <- data.table(data) dt[ ,b1 := {   bb <- rle(b==1)   r <- bb$values   r[r] <- seq_len(sum(r))   bb$values <- r   inverse.rle(bb) } ]  dt[b1 == 1, sum(a)] # [1] 2 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -