0

I got a list of data frames, such as c(df01,df02,df03).

Each data frame has three columns, c("A", "B", "C").

I want to write a for loop to modify each column for each data frame. I tried:

for (df in c("df01", "df02", "df03")) {
   for (col in c("A", "B", "C")) {
      get(df)[[col]] <- 0
   }
}

I learned from this post that we cannot assign value to the result of the get() function in R.

I also tried

assign(df[[col]], 0)

But this also does not work. The assign() function only assigns a value to a name, but here df[[col]] is not a name, but a column.

How can I fix this?

2
  • 1
    Do you have a "list of data.frames' or a "vector of names of data.frames"? Because it would be best to just have a list that you can iterator over so you don't have to bother with get/assign -- those aren't very R-like solutions. If you have a list, you can just lapply over it to transform it. Commented Aug 19, 2020 at 3:20
  • 1
    Referenced in Meta Stack Overflow question Duplicate of Stack Overflow?. Commented Aug 19, 2020 at 18:25

1 Answer 1

2

You could get the dataframes in a list and use lapply to change the columns

df_vec <- c("df01","df02","df03")
col_vec <- c("A","B","C")
result <- lapply(mget(df_vec), function(x) {x[col_vec] <- 0;x})

For these changes to reflect in original dataframe use list2env :

list2env(result, .GlobalEnv)
Sign up to request clarification or add additional context in comments.

4 Comments

Or lapply(mget(df_vec), replace, col_vec, 0) since the col_vec selects the columns by default.
@Ronak Thanks!! I got it to work, but I got a warning "number of items to replace is not a multiple of replacement length". Do you know possibly know the reason?
I'm also wondering what's the difference between df [ [colname] ] and df [colname];
Using double bracket you can select only one element and with single bracket you can select more than one. Here is a link explaining this in detail stackoverflow.com/questions/1169456/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.