0

I hope you're all keeping COVID-free! I'm trying to use pivot_wider to do the same thing as unstack on a simple data frame but without success. I hope someone can set me right. My data has two columns: a "group" column and a numeric values column. I'd like to reshape it so the data values for each group are in two separate columns named with the group names. I haven't found an answer online. The closest thing I've found is when there is also a third ID-type column like here but I don't have a column like that. I'm getting the same three warning messages as in that post. Here's an example, starting with the unstacked data, using pivot_longer to stack it and then trying to get back to where I started with pivot_wider. (Data is generated randomly.)

dd1 <- as.data.frame(matrix(rpois(10, 5), nrow = 5))
dd1

  V1 V2
1  2  8
2  6  4
3  5  4
4  4  7
5  6  3

library(tidyverse)
dd2 <- dd1 %>%
  pivot_longer(cols = c("V1", "V2"))
dd2

# A tibble: 10 x 2
   name  value
   <chr> <int>
 1 V1        2
 2 V2        8
 3 V1        6
 4 V2        4
 5 V1        5
 6 V2        4
 7 V1        4
 8 V2        7
 9 V1        6
10 V2        3

pivot_longer works nicely. Now back to the start with pivot_wider.

dd2 %>% pivot_wider(names_from = name, values_from = value)

Values are not uniquely identified; output will contain list-cols.
* Use `values_fn = list` to suppress this warning.
* Use `values_fn = length` to identify where the duplicates arise
* Use `values_fn = {summary_fun}` to summarise duplicates

# A tibble: 1 x 2
  V1        V2       
  <list>    <list>   
1 <int [5]> <int [5]>

I'd appreciate any help to sort this out.

istibar
  • 33
  • 5

0 Answers0