所以,我有 6 個資料框,都看起來像這樣(具有不同的值):

現在我想在該國家/地區的所有資料框中創建一個新列。然后我想把它轉換成一個長的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]
就是這樣,它不對資料幀進行操作。我很確定我犯了一個愚蠢的錯誤,但是我在論壇上在線查看并無法弄清楚。
uj5u.com熱心網友回復:
也許你可以更換
trial$country <- rownames(trial)
經過
trial <- cbind(trial, rownames(trial))
uj5u.com熱心網友回復:
這是一個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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414345.html
標籤:
