Anubhav Dikshit
Anubhav Dikshit

Reputation: 1829

for loop to assign column values on dynamic number of data frames

I have multiple data frames called (df1, df2, df3, df4, etc.) with the following structure:

ID val1 val2
1  1    1
2  1    2
3  NA   3
4  NA   4
5  6    3
6  6    6

I want to assign the NA values in val1 with values in val2, I used the following to do so:

df1$val1[is.na(df$val1)] <- df1$val2[is.na(df1$val1)]

This works well!

Problem:

I don't want to write multiple such statements to handle this, because number of data frames is large say 10

I know how to dynamically create data frames but I can't do the same for this!

Inspiration:

for(i in 1:10){ 
  assign(paste("df", i, sep = ""), subset(df2, count == i))}

P.S: Merging df's together is not allowed

Upvotes: 2

Views: 421

Answers (1)

akrun
akrun

Reputation: 887501

We can place the datasets in a list and do the same operation. If we need to change the values in the original objects, wrap it with list2env

lst <- mget(paste0("df", 1:10))
list2env(lapply(lst, function(x) {i1 <- is.na(x$val1)
                         x$val1[i1] <- x$val2[i1]
                         x }), envir = .GlobalEnv)

This can be also done more efficiently with data.table

list2env(lapply(lst, function(x) setDT(x)[is.na(val1), val1:= val2]), 
                envir = .GlobalEnv)

Upvotes: 2

Related Questions