Home > other >  Looping through multiple lists
Looping through multiple lists

Time:05-02

How can one loop through multiple data sets in R, it seems a little elusive from Python.

We have 4 lists and want to simply remove all missing values.

Example:

a <- c(1,2,3, NA)
b <- c(1,NA,3, NA)

e <- c(1,2,3, 4)
f <- c(NA,2,3, NA)

is.na(a_df) ## -> TRUE

na_list = list(a, b, e, f)

What has been tried:

  1. Duplicating the code 4 times, which is DRY but works.
for (lst in na_list){
  lst <- zoo::na.aggregate(lst)
}
  1. Using Lappy
na_list <- lapply(na_list, zoo::na.aggregate)
> na_list
[[1]]
[1] 1 2 3 2

[[2]]
[1] 1 2 3 2

but..

> a 
[1]  1  2  3 NA

CodePudding user response:

Have revised according to updated question. Note that the input now shown in the question are numeric vectors, not R lists.

First create a named list L using mget and then apply na.aggregate to each component of L and finally write the components back out to the global environment; however, you might want to just keep the result as L2 since it is harder to debug code that overwrites variables.

library(zoo)

nms <- c("a", "b", "e", "f")

L <- mget(nms)
L2 <- lapply(L, na.aggregate)
list2env(L2, .GlobalEnv)

This would also work in place of the last 3 lines.

for(nm in nms) assign(nm, na.aggregate(get(nm)))
  • Related