簡體   English   中英

批量更改數據框? 如何將操作列表應用於多個數據幀?

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

所以,我有 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]

就是這樣,它不對數據幀進行操作。 我很確定我犯了一個愚蠢的錯誤,但是我在論壇上在線查看並無法弄清楚。

也許你可以更換

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM