![](/img/trans.png)
[英]Get column names and dataframe name from a list of dataframes into a single dataframe
[英]How to create a dataframe from a list of dataframes but have the column names be the list of dataframes?
我有這個數據框列表。 在各個數據框中,它們都有“國家”和“2009”列,因為這是我選擇使用的數據。 如何按國家/地區組合所有這些數據框,使用數據框的名稱作為我的單個 dataframe 的列(結果)? 我正在提供我的列表和數據框的樣子的圖片。
結果 dataframe 應該有 'water'、'childMort'、'totalFertility' 等列和 2009 COMPLETE 數據(沒有 nas 或沒有匹配國家的列),但行將是國家,例如:
country water childMort totalFertility ...
Albania 91.4 13.30 1.65
Angola 50.4 120.00 6.16
Afghanistan 48.3 88.00 5.82
我嘗試使用如下減少:
country2009df %>% reduce(left_join)
但我得到一個錯誤
Error in `fn()`:
! join columns must be character vectors.
更新:我嘗試使用bind_rows,它給了我國家,但還有'2009'作為我不想要的另一列,我想要的列名在'name'列下。
bind_rows(country2009df, .id='name')
name country 2009
1 water Aruba 97.30
2 water Afghanistan 48.30
3 water Angola 50.40
4 water Albania 91.40
5 water Andorra 100.00
您可以使用data.table
package:
library(data.table)
country2009df_binded <- rbindlist(
l = lapply(
X = names(country2009df),
FUN = function(i)
{
res <- country2009df[[i]]
res$what <- i
return(res)
}
)
)
country2009df_binded <- dcast(data = country2009df_binded, formula = country ~ what, value.var = "2009")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.