1

Using R, I wanted to save each variable's value when running lapply(). Below is what I tested now:

list_C <- list()
list_D <- list()
n <- 1

data_partition <- split(data, with(data, paste(A, B, sep=":")))
final_result <- lapply(data_partition,
                       function(dat) {
                         if(... condition ...) {
                           <Some R codes to run>
                           list_C[[n]] <- dat$C
                           list_D[[n]] <- dat$D
                           n <- n + 1
                         }
                       })

However, after running the code, 'n' remains just '1' and there's no change. How can I change the variable of 'n' to get the right saving lists of 'list_C' and 'list_D'?

SeungCheol Han
  • 113
  • 1
  • 7
  • 2
    You could use `n <<- n + 1` but generally it's considered bad practice to modify variables in global scope within functions (ideally functions shouldn't have side effects). – MrFlick May 20 '15 at 05:29
  • 1
    @MrFlick If my approach is not recommended at all, can you suggest any workaround for me? – SeungCheol Han May 20 '15 at 05:32
  • 3
    Your example isn't [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) because it's missing chunks. It's unclear exactly what the desired behavior is. Ideally you would define all variables, give sample input and show the desired output. – MrFlick May 20 '15 at 05:33

0 Answers0