jmutua
jmutua

Reputation: 293

Transform long format dataframe with multiples sets of columns into wide format

How can you transform a long format dataframe with multiple sets of columns into a wide format?

df <- data.frame(
  id = c(1, 2),
  uid = c("m1", "m2"),
  germ = c(23, 24),
  category = c("x1", "x2"),
  mineral = c(78, 10))

Names come from uid and category while Values come from germ and mineral. I have tried working on this with the code below but the names are not what I want

out_df <- df %>% 
  tidyr::pivot_wider(names_from = c(uid, category), values_from = c(germ, mineral))

Here is what I would like my output to look like

out_df <- data.frame(id = c(1, 2),
                     m1 = c(23, NA),
                     m2 = c(NA, 24),
                     x1 = c(78, NA),
                     x2 = c(NA, 10))

Upvotes: 1

Views: 42

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 52409

An easy way to get the expected output is to apply pivot_wider twice:

df %>% 
  pivot_wider(names_from = "uid", values_from = "germ") %>% 
  pivot_wider(names_from = "category", values_from = "mineral")

# A tibble: 2 x 5
#     id    m1    m2    x1    x2
#  <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1    23    NA    78    NA
#2     2    NA    24    NA    10

Upvotes: 3

Related Questions