0

My problem in R is that I want to replace values in a data frame by checking a condition for any entry (namely if it is NA) and subsequently inserting a value selected from a list. The nested for loops seem to work but they are way too slow!

for (i in 1:nrow(data)) {
for (j in 1:ncol(data)) {

 if (is.na(data[i,j]) == FALSE){
 df[i,j] <- some_list[[j]]$freq[ which(some_list[[j]][1] == data[i,j]) ]       
 }

 if (is.na(data[i,j]) == TRUE){
   df[i,j] <- NA
 }

}
}

I would prefer a solution using apply in combination with ifelse or any other fast approach, but I don't see it unfortunately.

phiver
  • 23,048
  • 14
  • 44
  • 56
K.O.T.
  • 111
  • 10
  • What is *some_list*? Please explain in words what you are trying to do. Loop through every column of data frame and check values in *freq* element of *some_list*? We need background and some actual/sample data to illustrate. Otherwise this reads as an [XY Problem](https://meta.stackexchange.com/a/66378): asking help with your proposed *Y* solution without explaining the *X* problem. – Parfait Aug 21 '18 at 15:10
  • some_list is a list that contains elements which are data frames each with a column "freq". If some element data[i,j] is not NA, I want to replace df[i,j] by an entry of an element of list element nr. j which is selected according to the condition in [ ]. If some data[i,j] is NA, I want to insert NA for df[i,j] I'll try to work out a minimal example. – K.O.T. Aug 21 '18 at 15:18
  • 1
    Please edit your post with this explanation (and delete this long comment as will I). Also, give slightly more background, too, and not just *how-to*. For instance how is *df* and *some_list* created as they seem related and share same structure? Some `dput` and sample data always helps *show* instead of *tell* with words. See: [How to make a great R reproducible example](https://stackoverflow.com/q/5963269/1422451). – Parfait Aug 21 '18 at 15:29

0 Answers0