Reputation: 15
After using pivot_wider(), I have a data frame like this:
country | year | variable 1 | variable 2 |
---|---|---|---|
A | 2000 | 0.5 | NA |
A | 2000 | NA | 68 |
B | 2000 | NA | 55 |
B | 2000 | 0.9 | NA |
What is the easiest way to make it like this:
country | year | variable 1 | variable 2 |
---|---|---|---|
A | 2000 | 0.5 | 68 |
B | 2000 | 0.9 | 55 |
Thank you
Before pivot_wider(), the data frame was like this:
country | year | variables | values |
---|---|---|---|
A | 2000 | variable 1 | 0.5 |
A | 2000 | variable 2 | 68 |
B | 2000 | variable 1 | 0.9 |
B | 2000 | variable 2 | 55 |
Code:
data <- data %>% pivot_wider(names_from = variables, values_from = values)
Upvotes: 0
Views: 30
Reputation: 26218
Correct way for pivot_wider
data <- data %>% pivot_wider(id_cols = c(country, year), names_from = variables, values_from = values)
Upvotes: 1