EN VI

How to apply function to dataframes within a list?

2024-03-11 21:30:05
How to apply function to dataframes within a list?

for these dataframe:

 d1 <- data.frame(y1=c(1,2,3), y2=c(4,5,6))
 d2 <- data.frame(y1=c(3,2,1), y2=c(6,5,4))
 d3 <- data.frame(y1=c(6,5,4), y2=c(3,2,1))
 d4 <- data.frame(y1=c(9,9,9), y2=c(8,8,8))

dat=sapply(paste('d', seq(2,4,1), sep=''), get, environment(), simplify = FALSE)

For instance i can do this manually

 scale(as.numeric(dat$d2$y1))[,1]

but i want to do this to all data.frames d2$y1, d2$y2, d1$y1, d1$y .;;etc and get the output

Solution:

Update

lapply(
    dat,
    \(y) {
        transform(
            y,
            y1 = scale(y1)
        )
    }
)

If you want to change y1 columns only

Previous

You can simply run mget (rather than sapply + get)

> (dat <- mget(paste0("d", seq(2, 4, 1))))
$d2
  y1 y2
1  3  6
2  2  5
3  1  4

$d3
  y1 y2
1  6  3
2  5  2
3  4  1

$d4
  y1 y2
1  9  8
2  9  8
3  9  8

If you want to apply a function to a list of dataframes, you can use lapply(dat, f), where f is the function you will proceed with over each dataframe., for example

lst <- lapply(
    dat,
    \(y) list2DF(lapply(
        y,
        scale
    ))
)

which gives

$d2
  y1 y2
1  1  1
2  0  0
3 -1 -1

$d3
  y1 y2
1  1  1
2  0  0
3 -1 -1

$d4
   y1  y2
1 NaN NaN
2 NaN NaN
3 NaN NaN

Furthermore, if you want to overwrite d2, d3 and d4 by the updated values, you can further run

list2env(lst, envir = .GlobalEnv)
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login