Using gather() to gather two (or more) groups of columns into two (or more) key-value pairs [duplicate]

拟墨画扇 提交于 2019-11-29 16:06:46

You can use something like the following. I'm not sure from your current approach if this is exactly your desired output or not since it seems to contain a lot of redundant information.

df %>%
  gather(val, var, -ID) %>%
  extract(val, c("value", "time"), regex = "([a-z]+)([0-9]+)") %>%
  spread(value, var)
# # A tibble: 10 × 4
#       ID  time letter measure
# *  <int> <chr>  <chr>   <chr>
# 1      1     1      a       1
# 2      1     2      f       6
# 3      2     1      b       2
# 4      2     2      g       7
# 5      3     1      c       3
# 6      3     2      h       8
# 7      4     1      d       4
# 8      4     2      i       9
# 9      5     1      e       5
# 10     5     2      j      10

This is much more easily done with melt + patterns from "data.table":

library(data.table)
melt(as.data.table(df), measure.vars = patterns("measure", "letter"))

Or you can be old-school and just use reshape from base R. Note, however, that base R's reshape does not like "tibbles", so you have to convert it with as.data.frame).

reshape(as.data.frame(df), direction = "long", idvar = "ID", 
        varying = 2:ncol(df), sep = "")

We can use melt from data.table which can take multiple measure patterns

library(data.table)
melt(setDT(df), measure = patterns("^measure", "^letter"), 
          value.name = c("measure", "letter"))
#     ID variable measure letter
# 1:  1        1       1      a
# 2:  2        1       2      b
# 3:  3        1       3      c
# 4:  4        1       4      d
# 5:  5        1       5      e
# 6:  1        2       6      f
# 7:  2        2       7      g
# 8:  3        2       8      h
# 9:  4        2       9      i
#10:  5        2      10      j
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!