Jdan Jdan - 1 month ago 8
R Question

Loop through rows and keep column values less than random value R

I have a matrix similar to the following that have cumulative sums of random values.

dist<-.25
mat<-matrix(data=runif(150,25,55)*dist, nrow = 500,ncol=150)
mat = t(apply(mat, 1, cumsum))


and what I'd like to do is:

For each row generate a new random value

RV<-runif(1,1,800)


and for all columns in that row less than "RV" make them = "na". I would also like retain (cbind) the random value "RV" for each row

In the end I would like a matrix (or dataframe) where the first column is the random value "RV" generated for each row and all columns in that row have values less than "RV" or are otherwise "na"

I have an idea of how to identify the right values for 1 row at a time but I can't seem to figure out how to do this with the apply functions. Perhaps I'll have to for loop it but my real data set has close to 100,000 rows so I'd like to avoid a for loop if possible

Y<-data.frame(mat)
Y[1, which(Y[1,1:150]< RV)]


I thought this was going to be easy but totally stumped. Any ideas would be greatly appreciated

Answer

Here's a solution using apply:

mat2 <- apply(mat,
              MARGIN = 1,
              function(x) {
                 zx <- runif(1,1,800)
                 x[x > zx] <- NA
                 return(append(zx, x))
              })

mat2 <- t(mat2)