r - Conditional vectorization -
given data frame below:
set.seed(123) df1 <- data.frame(v1=sample(c(0,1,2),100,replace=true), v2=sample(c(2,3,4),100,replace=true), v3=sample(c(4,5,6),100,replace=true), v4=sample(c(6,7,8),100,replace=true), v5=sample(c(6,7,8),100,replace=true))
i want sum each row, starting first column value >=2, , ending column value >6, else sum until end of row.
how in vectorized fashion?
update: not homework assignment. want more examples of vectorization code can study , learn from. had above before, couldn't figure out apply
syntax particular task , resorted for
loops.
this appeared r-like approach don't consider "vectorized" in r meaning of term:
apply( df1, 1, function(x) sum( x[which(x>=2)[1]: min(which(x>6)[1], 5, na.rm=true)] ) ) #--------- [1] 15 22 16 19 17 17 23 21 14 13 18 13 16 23 15 18 16 21 16 19 17 23 21 18 [25] 21 24 15 20 15 18 17 24 19 18 19 15 18 17 15 17 14 21 13 19 15 15 15 15 [49] 21 19 21 15 17 18 14 17 15 16 22 16 23 22 17 21 17 16 23 23 16 14 18 13 [73] 18 15 17 17 17 20 20 16 17 16 16 16 14 16 20 23 23 24 14 18 16 17 22 23 [97] 23 19 20 17
Comments
Post a Comment