R mutated by data list

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 trying to apply mutate function to each datafile, but I am getting an "incompatible with STRSXP" error that I am confused with.

here is my code which is giving 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 data frame. It uses the mutant function and creates a new column named "NewColumn1" that divides the first column by half the second column. It does something similar for the next column.

Am I in the right ball with this code, or can I not use mutation when looping even though dfs is listed?

+3


source to share


2 answers


It seems that you are on the right track, but the way you replace the elements of the original list is a little flawed. While this can be achieved in a number of ways, at the core of where you started:

for cycle

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 map

from the package purrr

.

I hope one of them serves a purpose.

+6


source


Here is an option with map

fromtidyverse



library(tidyverse)
ldf %>%
   map(~mutate(., NewColumn1 = first/(second*2), NewColumn2 = first/(second*3)))

      

+3


source







All Articles