0

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)
5
  • Since that result is post-pivot_longer, that suggests the pivot was either done incorrectly or should not have been done in the first place. Please post the pre-pivot data and the code you used to get to this. Commented Jan 4, 2021 at 16:41
  • @r2evans sorry, I meant pivot_wider. Updated post Commented Jan 4, 2021 at 16:49
  • When I run your code on that new batch of data, I get your desired output. Commented Jan 4, 2021 at 16:51
  • My pivot_wider was wrong. Thank you! Commented Jan 4, 2021 at 16:57
  • See the answer below. You have to specify id columns in argument id_cols Commented Jan 4, 2021 at 16:57

1 Answer 1

1

Correct way for pivot_wider

data <- data %>% pivot_wider(id_cols = c(country, year), names_from = variables, values_from = values)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.