Spread rows into columns in R

Viewed 895

I have two columns: one that contains the name of the variables and one that contains their respective values. It is only two variables, with three observations each, like in the example that follows:

library(tidyverse)

tibble(
  var = rep(letters[1:2],3),
  vals = c(1:6)
) %>% 
  arrange(var)

# A tibble: 6 x 2
  var    vals
  <chr> <int>
1 a         1
2 a         3
3 a         5
4 b         2
5 b         4
6 b         6

The problem is that I need to turn a and b into columns, like in this expected output:

# A tibble: 3 x 2
      a     b
  <dbl> <dbl>
1     1     2
2     3     4
3     5     6

I have tried doing this with tidyr::spread with no success. Any ideas?

2 Answers

You could use unstack

tbl <- tibble(
  var = rep(letters[1:2],3),
  vals = c(1:6)
) %>% 
  arrange(var)

unstack(tbl, vals ~ var)
#  a b
#1 1 2
#2 3 4
#3 5 6

We need a sequence column after grouping by 'var'. It will also make sure that for groups that are not having the same number of elements, the remaining values can be filled by a choice value (by default, it is NA)

library(tidyverse)
tbl %>% 
  group_by(var) %>% 
  mutate(rn = row_number()) %>% 
  spread(var, vals) %>% 
  select(-rn)
# A tibble: 3 x 2
#      a     b
#  <int> <int>
#1     1     2
#2     3     4
#3     5     6

data

tbl <- tibble(
  var = rep(letters[1:2],3),
  vals = c(1:6)
   ) %>% 
     arrange(var)
Related