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?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Squirrel K
  • 25
  • 3
  • 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. – MrFlick Aug 19 '20 at 03:20
  • 1
    Referenced in Meta Stack Overflow question *[Duplicate of Stack Overflow?](https://meta.stackoverflow.com/questions/400441/duplicate-of-stack-overflow)*. – Peter Mortensen Aug 19 '20 at 18:25

1 Answers1

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)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Or `lapply(mget(df_vec), replace, col_vec, 0)` since the `col_vec` selects the columns by default. – thelatemail Aug 19 '20 at 03:14
  • @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? – Squirrel K Aug 19 '20 at 15:08
  • I'm also wondering what's the difference between df [ [colname] ] and df [colname]; – Squirrel K Aug 19 '20 at 15:11
  • 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 https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el – Ronak Shah Aug 19 '20 at 15:20