Search code examples
rloopsdplyrassign

How to use loop to apply a function in several dataframes and paste the result in the specific dataframe in R


I have two dataframes AAA, BBB (and will have more dataframes, so it's worth using loop)

And I have a user-defined function V2.Scale_function

I want to apply V2.Scale_function to the #21 column of AAA and BBB

I tried

library("dplyr")
library("tidyverse")

tables = list ("AAA", "BBB")

for(table in tables){
  assign(table, get(table) %>%
           mutate(V2.Scale= apply(table[, 21], 1, V2.Scale_function)))   ### tables here has errors
}

Then I got an error:

Error in `mutate()`:
! Problem while computing `V2.Scale = apply(table[, 21], 1, V2.Scale_function)`.
Caused by error in `table[, 21]`:
! incorrect number of dimensions
Run `rlang::last_error()` to see where the error occurred.

I am wondering how to fix this bug. Thank you.


Solution

  • I think I figured out:

    library("dplyr")
    library("tidyverse")
    
    tables = list ("AAA", "BBB")
    
    ### should be get(table) instead of (table)
    for(table in tables){
        assign(table, get(table) %>%
        mutate(V2.Scale= apply(get(table)[, 21], 1, V2.Scale_function)))   
    }