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?
Here is an option with map
from tidyverse
library(tidyverse)
ldf %>%
map(~mutate(., NewColumn1 = first/(second*2), NewColumn2 = first/(second*3)))
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 (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(ldf, function(x) {
mutate(x,
new_col_one=first/(second * 2),
new_col_two=first/(second * 3))
})
This will create a new list
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.
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