1

I'm trying to stack rows of data into columns so that the variables in another column will repeat. I would like to turn something like this

tib <- tribble(~x, ~y, ~z, "a", 1,2, "b", 3,4)
> tib
# A tibble: 2 x 3
  x         y     z
  <chr> <dbl> <dbl>
1 a         1     2
2 b         3     4

into

t <- tribble(~X, ~Y, "a", 1, "a", 2, "b", 3, "b", 4)
> t
# A tibble: 4 x 2
  X         Y
  <chr> <dbl>
1 a         1
2 a         2
3 b         3
4 b         4

Thanks for your help and sorry if I've missed this solution somewhere. I did a search, and tried applying gather(), spread(), but couldn't get it to work out.

jim
  • 175
  • 8

2 Answers2

1

Here is an example using data.table::melt():

# Assuming your data is a data.frame
xyz <- data.frame(
  x = c("a", "b"),
  y = c(1, 3),
  z = c(2, 4)
)

library(data.table)
melt(xyz, id.vars = "x")[c(1, 3)]

  x value
1 a     1
2 b     3
3 a     2
4 b     4
s_baldur
  • 29,441
  • 4
  • 36
  • 69
0

This can be done with many packages. One possibility is tidyr and the function gather (link)

EDIT Using @sindri_baldur data:

library(tidyr)
xyz %>% 
  gather(class, measurement, -x)
c1au61o_HH
  • 867
  • 7
  • 14