Home > Net >  How to extract cell values from dataframe to new object with a for loop in R?
How to extract cell values from dataframe to new object with a for loop in R?

Time:12-01

I have two dataframes. One, dataA, contains columns X, Y, and Z. The other, dataB, is a large matrix (135x240) where in some cells there are probabilities but most cells contain 0. I need to extract cell values from dataB and create a new object from them. Indices for the cells to extract are in dataA, X is the columns, Y is the rows, but only if Z == 1121.

So far I've tried this, and some variations of it, but nothing works. I'd be very grateful for any and all help.

new_object <- dataB %>% 
  for (val in dataA$Z=="1121") {mutate (prob = select(dataB[dataA$Y, dataA$X])}

CodePudding user response:

Base R is probably a better choice here:

    z_index <- dataA$Z == "1121"
subset_function <- function(x, y, dat) dat[y, x]
X <- dataA$X[z_index]
Y <- dataA$Y[z_index]
new_object <- mapply(FUN = subset_function, x = X, y = Y, MoreArgs = list(dat = dataB))
  • Related