mapply - R Vectorization: How to return the index of the first element of each row in a matrix that meets a condition and sum all elements until that index? -


i looking vectorized solution. generate 100 samples of 10 draws replacement. next, want find first index of first element of matrix of cumulative sums means condition, say, >=10. then, want sum elements of each row until index of first element meeting condition. mwe:

set <- c(1, 5, 7, 13, 15, 17) samp <- samp <- matrix(sample(set, size = 100*10, replace = true), nrow=simcount) # generate 100 samples of 10 draws b <- matrix(apply(samp, 1, cumsum),    nrow = 100, byrow=true) >= 10 # compare each element 10, return boolean 

i'm not sure how use apply which(x)=="true". tried few variations i'm not sure how code correctly.

after that, i'll able use apply(b, 1, min) return first element (minimum index) each row >=10.

set seed please "random" examples:

set.seed(111) samp <- matrix(sample(1:5, s=1000, r=t), nrow=100) (answer1 <- samp[which(apply(samp,1,function(x)sum(x)>30)),1]) # [1] 4 3 3 3 1 1 3 5 2 4 2 5 4 2 4 1 3 2 4 4 5 4 2 4 5 5 4 5 3 3 1 1 2 1 4 3 4 5 #[39] 1 5 1 4 4 3 3 2 5 5 

explanation:

apply(samp,1, function(x) sum(x) > 30)
well, if add 10 positive integers, >=10 true. apply "samp" each row function.

which(x) returns index of true values of x. (the rows of interest)

samp[(rows returned which), (1)st column] ... basic indexing

unwrap step step outside in better understanding.

b <- matrix(apply(samp, 1, cumsum), nrow=100, byrow=t)>=10 apply(b,1,function(x)which(x)[1]) #  [1] 4 5 4 3 3 5 3 4 3 4 3 3 5 4 5 4 2 4 3 6 3 3 5 4 3 3 2 4 4 6 3 4 3 4 5 4 4 # [38] 4 3 5 3 6 3 3 5 5 3 3 4 6 4 5 4 4 3 4 4 4 2 5 3 4 3 4 4 3 4 6 3 5 4 4 4 4 # [75] 3 3 5 4 4 3 3 4 4 5 4 4 4 3 4 3 5 4 3 5 3 6 4 5 5 3 

Comments