Does pivot_wider need any other info than names_from and values_from

Viewed 44

I was wondering why my pivot_wider() call below doesn't make my_data in the wide format?

Does pivot_wider() need any other info than names_from and values_from?

library(tidyverse)

  before <-c(200.1, 190.9, 192.7, 213, 241.4, 196.9, 172.2, 185.5, 205.2, 193.7)
  after <-c(392.9, 393.2, 345.1, 393, 434, 427.9, 422, 383.9, 392.3, 352.2)

  my_data <- data.frame( 
    group = rep(c("before", "after"), each = 10),
    weight = c(before,  after)
  )  

  pivot_wider(my_data, values_from = weight, names_from = group)
1 Answers

We need a sequence to account for the duplicate elements in 'weight'. It can be created with either group_by(group) %>% mutate(rn = row_number()) or more easily from rowid of data.table

library(data.table)
library(dplyr)
library(tidyr)
my_data %>%
    mutate(rn = rowid(group)) %>%
    pivot_wider(values_from = weight, names_from = group) %>%
    select(-rn)

-output

# A tibble: 10 x 2
#   before after
#    <dbl> <dbl>
# 1   200.  393.
# 2   191.  393.
# 3   193.  345.
# 4   213   393 
# 5   241.  434 
# 6   197.  428.
# 7   172.  422 
# 8   186.  384.
# 9   205.  392.
#10   194.  352.

In base R, we can use unstack

unstack(my_data, weight ~ group)
Related