[英]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):所以,我有 6 个数据框,都看起来像这样(具有不同的值):
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.
然后我想把它转换成一个长的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 -这是一个
tidyverse
的尝试 -
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.