Home > OS >  How do I pivot_wider a char column?
How do I pivot_wider a char column?

Time:12-03

I'm trying to pivot_wider a tibble of random alpha strings

stri_rand_strings(252, 5, '[a-z]') %>%
sort() %>%
as_tibble() %>%
mutate(id = row_number(),
       col = rep(letters[1:4], each = length(value) / 4)) %>%
pivot_wider(names_from = col, values_from = value)

I get three columns of NA in a tibble (252 x 5):

# A tibble: 252 × 5
      id a     b     c     d    
   <int> <chr> <chr> <chr> <chr>
 1     1 aarup NA    NA    NA   
 2     2 abhir NA    NA    NA   
 3     3 afpgt NA    NA    NA   
 4     4 apjts NA    NA    NA   
 5     5 arlst NA    NA    NA   
 6     6 awkjn NA    NA    NA   
 7     7 babro NA    NA    NA   
 8     8 bbrpn NA    NA    NA   
 9     9 bbrzt NA    NA    NA   
10    10 bedzs NA    NA    NA   
# … with 242 more rows

instead of the desired 63 x 5.

CodePudding user response:

your id-column is messing everything up. rownumbers are unique, so casting to wide does not make sense, since you have got unique identifiers.

try something like

stringi::stri_rand_strings(252, 5, '[a-z]') %>%
  sort() %>%
  as_tibble() %>%
  mutate(id = rep(1:(length(value) / 4), 4),  # !! <-- !!
         col = rep(letters[1:4], each = length(value) / 4)) %>%
  pivot_wider(names_from = col, values_from = value)

# A tibble: 63 x 5
      id a     b     c     d    
   <int> <chr> <chr> <chr> <chr>
 1     1 ababk glynv mottj tqcbv
 2     2 abysq gmfhc mujcw twjix
 3     3 aerkp godcs mycak tzqny
 4     4 agtoa gpler naetp ucuvg
 5     5 ahebl grqgz nfali ufbqv
 6     6 amdvv gswwu nhmnu ulgup
 7     7 apgut gvkwh nkcks umwih
 8     8 atgxy gynef nkklm uojxc
 9     9 bcklx hcdup nngfz upfhx
10    10 bcnxz hcpzy nnvpd uqlgs
# ... with 53 more rows
  • Related