我的資料按以下方式排列:
| 行業 | 年 | 國家 | 價值 |
|---|---|---|---|
| Ind_A | 1999 | A國 | 1245 |
| Ind_A | 2000 | B國 | 132 |
| Ind_B | 2000 | A國 | 145 |
| IND_C | 2000 | B國 | 122 |
我想重新排列這些資料,使其看起來像這樣:
| 國家 | 年 | 行業 A 值 | Ind_B 值 | Ind_C 值 |
|---|---|---|---|---|
| A國 | 1999 | 1245 | 不適用 | 不適用 |
| A國 | 2000 | 不適用 | 145 | 不適用 |
| B國 | 2000 | 不適用 | 不適用 | 122 |
似乎我應該能夠使用 pivot_longer() 函式來實作這一點,但我的嘗試無法產生我正在尋找的東西。
我嘗試以多種方式使用 pivot_longer。下面的代碼可能是我得到的最接近的代碼。它結合了國家和年份組合作為個人價值,這就是我想對行業和價值做的事情。
df_wide <- df_long %>% pivot_wider(names_from = c(Country, Year), values_from = c(Value), values_fn = list)
uj5u.com熱心網友回復:
你需要設定names_from = "Industry,你會做對的
df %>%
pivot_wider(names_from = "Industry", values_from = "Value") %>%
arrange(Country)
# A tibble: 3 × 5
Year Country Ind_A Ind_B Ind_C
<int> <chr> <int> <int> <int>
1 1999 CountryA 1245 NA NA
2 2000 CountryA NA 145 NA
3 2000 CountryB 132 NA 122
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/530792.html
標籤:rdplyr重塑
上一篇:使用dplyr將資料框中的值(基于特定分組)乘以單獨的矩陣
下一篇:從串列中回傳空列的名稱
