2

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

1
  • 1
    @RonakShah: Made the change sorry, yes i meant assign Commented Jan 5, 2017 at 7:10

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I tired both the methods, data.table method is definitely easier to understand thanks a lot
@akrun thank you for list2env() I needed this func at my work! great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.