Home > front end >  R -- Pivot Wider Over Multiple Names and Values
R -- Pivot Wider Over Multiple Names and Values

Time:11-10

I have data arranged in the following manner:

Industry Year Country Value
Ind_A 1999 Country A 1245
Ind_A 2000 Country B 132
Ind_B 2000 Country A 145
Ind_C 2000 Country B 122

I would like to re-arrange this data so that it looks like this:

Country Year Industry A Value Ind_B Value Ind_C Value
Country A 1999 1245 NA NA
Country A 2000 NA 145 NA
Country B 2000 NA NA 122

It seems like I should be able to use pivot_longer() function to achieve this but my attempts have not been able to produce what I am looking for.

I tried to use pivot_longer in a variety of ways. The code below is probably the closest I've gotten. It combines country and year combinations as individual values, which is what I would like to do with industry and value.

df_wide <- df_long %>% pivot_wider(names_from = c(Country, Year), values_from = c(Value), values_fn = list)

CodePudding user response:

You need to set names_from = "Industry and you'll have it right

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
  • Related