Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205372

pivot_wider with duplicates

$
0
0

I have the following df

df <- structure(list(ID = c(1, 1, 1, 1, 1, 2, 2, 2, 2), value = c("p", 
"p", "p1", "p2", "p3", "a", "b", "c", "d"), i1 = c(1, 1, 1, 1, 
1, 1, 1, 1, 1)), row.names = c(NA, -9L), class = c("tbl_df", 
"tbl", "data.frame"))
     ID value    i1
  <dbl> <chr> <dbl>
1     1 p         1
2     1 p         1
3     1 p1        1
4     1 p2        1
5     1 p3        1
6     2 a         1
7     2 b         1
8     2 c         1
9     2 d         1

When I tried to pivot, I got an error saying there are duplicates.

df %>% pivot_wider(names_from = value, values_from = i1, values_fill = list(i1 = 0))
Warning message:
Values in `i1` are not uniquely identified; output will contain list-cols.
* Use `values_fn = list(i1 = list)` to suppress this warning.
* Use `values_fn = list(i1 = length)` to identify where the duplicates arise
* Use `values_fn = list(i1 = summary_fun)` to summarise duplicates

I would like to identify what values are repeating for each unique ID so I could filter. Or maybe I could remove duplicates during the pivot_wider() step. The source code has name_repair which I set to "unique". Did not work!

The ideal output is:

    p  p1  p2  p3  a  b  c  d
1   1   1   1   1  0  0  0  0
2   0   0   0   0  1  1  1  1

Viewing all articles
Browse latest Browse all 205372

Trending Articles