Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through a list of data frames and mutate columns

Tags:

r

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 ?

like image 501
user3206440 Avatar asked Mar 21 '18 16:03

user3206440


1 Answers

The map-version looks as follows:

library(purrr) # part of the tidyverse
map(my.list, ~ mutate(.x, new = y1 + y2))

~ creates and anonymous function.

like image 168
Jannik Buhr Avatar answered Sep 19 '22 17:09

Jannik Buhr