简体   繁体   中英

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

So, I have 6 data frames, all look like this (with different values): 在此处输入图像描述

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.

maybe you can replace

trial$country <- rownames(trial)

by

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM