Home > Mobile >  Changing dataframes in bulk? How to apply a list of operations to multiple dataframes?
Changing dataframes in bulk? How to apply a list of operations to multiple dataframes?

Time:01-18

So, I have 6 data frames, all look like this (with different values): enter image description here

Now I want to create a new column in all the data frames for the country. Then I want to convert it into a long df. This is how I am going about it.

dlist<- list(child_mortality,fertility,income_capita,life_expectancy,population)

convertlong <- function(trial){
  trial$country <- rownames(trial)
  trial <- melt(trial)
  colnames(trial)<- c("country","year",trial)
}

for(i in dlist){
 convertlong(i)
}

After running this I get:

Using country as id variables
Error in names(x) <- value : 
  'names' attribute [5] must be the same length as the vector [3]

That's all, it doesn't do the operations on the data frames. I am pretty sure I'm taking a stupid mistake, but I looked online on forums and cannot figure it out.

CodePudding user response:

maybe you can replace

trial$country <- rownames(trial)

by

trial <- cbind(trial, rownames(trial))

CodePudding user response:

Here's a tidyverse attempt -

library(tidyverse)

#Put the dataframes in a named list. 
dlist<- dplyr::lst(child_mortality, fertility, 
                   income_capita, life_expectancy,population)
#lst is not a typo!!

#Write a function which creates a new column with rowname
#and get's the data in long format
#The column name for 3rd column is passed separately (`col`).
convertlong <- function(trial, col){
  trial %>%
    rownames_to_column('country') %>%
    pivot_longer(cols = -country, names_to = 'year', values_to = col)
}

#Use `imap` to pass dataframe as well as it's name to the function. 
dlist <- imap(dlist, convertlong)

#If you want the changes to be reflected for dataframes in global environment.
list2env(dlist, .GlobalEnv)
  •  Tags:  
  • Related