'values are not uniquely identified' error in pivot_wider()

I’m having a hard time understanding why I can’t get pivot_wider() to work with tibbles such as the following:

library(tidyr)
library(dplyr)

mi_2018<-tribble(
  ~party_name, ~district, ~party_votes,
  #--|--|----
  "DEM", "10th", 106061,
  "REP", "10th", 182808,
  "DEM", "11th", 181912,
  "REP", "11th", 158463,
  "DEM", "12th", 200588,
  "REP", "12th",  85115,
  "DEM", "13th", 169330,
  "DEM", "13th", 165355,
  "DEM", "14th", 214334,
  "REP", "14th", 45899
)  

Attempting to pivot to wider results in an error:

  mi_2018 %>%
  pivot_wider(names_from = party_name, values_from=party_votes)

But I don’t see what is causing this error. The tibble seems to mirror the structure of the example from pivot_wider():

  us_rent_income2<- us_rent_income %>%
  select(NAME, variable, estimate)

us_rent_income2 %>%
  pivot_wider(names_from = variable, values_from = estimate)

Which works as expected.

Could someone please explain what I am missing?

Hi,

There is a double "DEM" in the "13th" district, disrupting a 1:1 relation. When you change that, it runs OK.

> mi_2018<-tribble(                                   
+   ~party_name, ~district, ~party_votes,             
+   #--|--|----                                       
+   "DEM", "10th", 106061,                            
+   "REP", "10th", 182808,                            
+   "DEM", "11th", 181912,                            
+   "REP", "11th", 158463,                            
+   "DEM", "12th", 200588,                            
+   "REP", "12th",  85115,                            
+   "REP", "13th", 169330,                            
+   "DEM", "13th", 165355,                            
+   "DEM", "14th", 214334,                            
+   "REP", "14th", 45899                              
+ )                                                   
> mi_2018 %>%                                         
+   pivot_wider(names_from = party_name, values_from= 
party_votes)                                          
# A tibble: 5 x 3                                     
  district    DEM    REP                              
  <chr>     <dbl>  <dbl>                              
1 10th     106061 182808                              
2 11th     181912 158463                              
3 12th     200588  85115                              
4 13th     165355 169330                              
5 14th     214334  45899                              

JW

Thank you. I completely missed that in the bigger dataset!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.