[英]Changing dataframes in bulk? How to apply a list of operations to multiple dataframes?
現在我想在該國家/地區的所有數據框中創建一個新列。 然后我想把它轉換成一個長的df。 這就是我要做的事情。
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)
}
運行后我得到:
Using country as id variables
Error in names(x) <- value :
'names' attribute [5] must be the same length as the vector [3]
就是這樣,它不對數據幀進行操作。 我很確定我犯了一個愚蠢的錯誤,但是我在論壇上在線查看並無法弄清楚。
也許你可以更換
trial$country <- rownames(trial)
經過
trial <- cbind(trial, rownames(trial))
這是一個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.