【问题标题】:complex data restructuring - wide to long (multiple columns)复杂的数据重组 - 从宽到长(多列)
【发布时间】:2018-12-08 18:10:28
【问题描述】:

我想进行上述重组,但我正在努力使用gather(),因为要制作多个列...有谁知道这样做的方法吗?

【问题讨论】:

  • 请以可复制和粘贴的格式发布您的数据。没有图片。同时看看?reshape

标签: r reshape reshape2 melt


【解决方案1】:

这应该可行,虽然可能不是最优雅的:

library(reshape2)
library(tidyr)
library(dplyr)

示例数据(基于屏幕截图):

df <- tibble(id = c(1,2,3), 
         mathT1 = c(10, 9, 7),
         mathT2 = c(11, 6, 8),
         write1 = c(2, 3, 1),
         write2 = c(3, 5, 1),
         ses = c(3, 4, 5))

使用 reshape2、dplyr 和 tidyr 包编写代码:

df <- df %>%
  rename(math_1 = mathT1, math_2 = mathT2, 
         write_1 = write1, write_2 = write2, ses_1 = ses) %>%
  mutate(ses_2 = ses_1) %>%
  melt(id.vars = "id", variable.name = "var", value.name = "value") %>%
  separate(var, c("var", "time"), "_", extra = "merge") %>%
  spread(var, value)

【讨论】:

    【解决方案2】:

    这是reshape 的选项。

    names(df1)[ncol(df1)] <- "ses1"
    df1$ses2 <- df1$ses1 # according to your desired output
    out <- reshape(df1, varying = 2:7, direction = "long", sep = "")
    out[order(out$id), ]
    #    id time mathT write ses
    #1.1  1    1    10     2   3
    #1.2  1    2    11     3   3
    #2.1  2    1     9     3   4
    #2.2  2    2     6     5   4
    #3.1  3    1     7     1   5
    #3.2  3    2     8     1   5
    

    并不是说我们需要创建一个列ses2 来获得您想要的输出。如果您想要 NAs 而不是 ses2 的值出现的地方 - 我认为这是正确的,给定输入数据 - 请查看下面的 data.table 解决方案。


    使用来自data.tablemelt

    library(data.table)
    setDT(df1)
    melt(df1,
         id.vars = "id", 
         measure.vars = patterns("^mathT", "^write", "^ses"), 
         variable.name = "Time", 
         value.name = c("mathT", "write", "ses"))
    #   id Time mathT write ses
    #1:  1    1    10     2   3
    #2:  2    1     9     3   4
    #3:  3    1     7     1   5
    #4:  1    2    11     3  NA
    #5:  2    2     6     5  NA
    #6:  3    2     8     1  NA
    

    数据感谢@Pete!

    df1 <- data.frame(
      id = c(1, 2, 3),
      mathT1 = c(10, 9, 7),
      mathT2 = c(11, 6, 8),
      write1 = c(2, 3, 1),
      write2 = c(3, 5, 1),
      ses = c(3, 4, 5)
    )
    

    【讨论】:

      猜你喜欢
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 2017-08-08
      • 2012-12-01
      • 2021-06-25
      相关资源
      最近更新 更多