Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R mutating along a list of dataframes

Tags:

r

dplyr

df<- data_frame(first =seq(1:10), second = seq(1:10))
ldf <- list(df, df, df, df, df)
names(ldf) <- c('alpha', 'bravo', 'charlie', 'delta', 'echo')

I have this list of dataframes and I am attempting to apply the mutate function to each dataframe but I get a "not compatible with STRSXP" error that I am confused about.

here is my code that gives me the error.

for( i in seq_along(ldf)){
 ldf[[i]] <- mutate( ldf[[i]], NewColumn1= ldf[[i]][1]/(ldf[[i]][2] *2),
                               NewColumn2= ldf[[i]][1]/(ldf[[i]][2] * 3))
}

My intention is that the for loop goes to the first dataframe. It applys the mutate function and creates a new column called "NewColumn1" that divides the first column by two times the second column. It does something similar for the next column.

Am I in the right ballpark with this code or can I not use mutate when looping though dfs in a list?

like image 454
MappingDataNerdom Avatar asked Jun 25 '17 01:06

MappingDataNerdom


2 Answers

Here is an option with map from tidyverse

library(tidyverse)
ldf %>%
   map(~mutate(., NewColumn1 = first/(second*2), NewColumn2 = first/(second*3)))
like image 174
akrun Avatar answered Oct 15 '22 06:10

akrun


You seem to be on the right track, but the way you're substituting the elements of your original list is a bit faulty. While there are multiple ways this could be achieved, the following are in the realm of what you started with:

for-loop

for (df_name in names(ldf)) {
    ldf[[df_name]] <- mutate(ldf[[df_name]],
           new_col_one=first/(second * 2),
           new_col_two=first/(second * 3))
}

This actually overwrites the original list.

lapply

lapply(ldf, function(x) {
    mutate(x,
           new_col_one=first/(second * 2),
           new_col_two=first/(second * 3))
})

This will create a new list

Map

Map(function(x) {
    mutate(x,
           new_col_one=first/(second * 2),
           new_col_two=first/(second * 3))
}, ldf)

This will create a new list, as well.

You can also look into map from the purrr package.

I hope one of these serves a purpose.

like image 40
Abdou Avatar answered Oct 15 '22 07:10

Abdou