Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tidyr spread values values from two columns (and rename columns)

Tags:

r

dplyr

spread

I'm trying to build on code from R - tidyr - mutate and spread multiple columns, I'm sorry if this is redundant with other posts and would be grateful to be pointed to those posts if they're out there!

example <- data.frame(category = c("a", "b", "c", "a", "b", "c", "a", "b", "c"),
                      value1 = c(1,2,3,4,5,6,7,8,9),
                      value2 = c(10,20,30,40,50,60,70,80,90))

  category value1 value2
1        a      1     10
2        b      2     20
3        c      3     30
4        a      4     40
5        b      5     50
6        c      6     60
7        a      7     70
8        b      8     80
9        c      9     90

I understand how to pivot this to get the values from either value1 or value2

example %>% 
spread(category, value1)
  value2  a  b  c
1     10  1 NA NA
2     20 NA  2 NA
3     30 NA NA  3
4     40  4 NA NA
5     50 NA  5 NA
6     60 NA NA  6
7     70  7 NA NA
8     80 NA  8 NA
9     90 NA NA  9

But I'd like to

  1. mutate the names of the category column to reflect the 1 and 2 values, so there's two columns for each category

    1. populate the column values based on values_from = value1 or value2
a_v1  a_v2  b_v1  b_v2  c_v1  c_v2
1     10    2     20    3     30
4     40    5     50    6     60
7     70    8     80    9     90

I realize my desired output will result in more rows with NAs like in the spread above but that's okay!

like image 884
MayaGans Avatar asked Jan 18 '26 23:01

MayaGans


1 Answers

library(dplyr)
library(tidyr)
example %>% 
  pivot_wider(names_from = category,
              values_from = c(value1, value2)) %>% 
  unnest()
like image 176
Yuriy Saraykin Avatar answered Jan 20 '26 16:01

Yuriy Saraykin