with data frames like below, I want to use a for loop to iterate through each data frame and add some new column say new
& new1
to the data frames d1
and d2
. Below is what I have tried.
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))
my.list <- list(d1, d2)
for(df in my.list) {
df$new <- df$y1 + df$y2
df$new1 <- df$y1 - df$y2
}
However when I look at the original data frames d1
and d2
they do not show the new col new
.
> colnames(d1)
[1] "y1" "y2"
> colnames(d2)
[1] "y1" "y2"
How do I got about getting new columns added to the original data frames d1
and d2
?
The map-version looks as follows:
library(purrr) # part of the tidyverse
map(my.list, ~ mutate(.x, new = y1 + y2))
~
creates and anonymous function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With