1

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
  • 1
    Please don’t type in all caps - it is seen as shouting and considered rude. – user438383 May 01 '22 at 16:33
  • `lapply` and similar are your friends. Read the online help. – Limey May 01 '22 at 16:37
  • Hi limey, care to share an example of solving this, been struggling with "lappy" particularly. Thanks – afrologicinsect May 01 '22 at 16:40
  • Please make a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) or [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) with a sample input and your expected output. – Martin Gal May 01 '22 at 17:02
  • `pred_list <- lapply(pred_list, zoo::na.aggregate)`. – Rui Barradas May 01 '22 at 17:29

1 Answers1

2

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)))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thanks so much for pointing out the errors, my apologies. Edited the questions to something reproducible, the data sets are lists not **data frames**, and applying a *lappy* although works but not reproducing for each item in the list. Kindly help review. – afrologicinsect May 01 '22 at 17:56
  • Thanks so much! ```for(nm in nms) assign(nm, na.aggregate(get(nm)))``` worked fine. – afrologicinsect May 01 '22 at 19:31