【问题标题】:Create multiple varaibles when using reshape/cast r使用 reshape/dcast r 时创建多个变量
【发布时间】:2018-05-27 13:24:51
【问题描述】:

我正在处理调查数据,并且在某些情况下,受访者多次回答了调查,因此存在于数据中的多行中。像这样:

Id Question1
1     5
1     3
2     3
3     5
4     1

我想将数据转换/重塑为宽格式,这样我可以得到它:

Id Question1 Question1.v2
1     5          3
2     3        missing  
3     5        missing
4     1        missing

【问题讨论】:

    标签: r casting reshape


    【解决方案1】:

    这应该对你有帮助:

    df = read.table(text = "
    Id Question1
    1     5
    1     3
    2     3
    3     5
    4     1
    ", header=T)
    
    library(dplyr)
    library(tidyverse)
    
    df %>%
      group_by(Id) %>%
      mutate(row = paste0("Question1.v", row_number())) %>%
      ungroup() %>%
      spread(row, Question1)
    
    # # A tibble: 4 x 3
    #      Id Question1.v1 Question1.v2
    # * <int>        <int>        <int>
    # 1     1            5            3
    # 2     2            3           NA
    # 3     3            5           NA
    # 4     4            1           NA
    

    我建议您不要使用missing,而是使用NA,这样您仍然可以将变量视为数字。

    如果您出于任何原因想要完全匹配您的输出,请尝试以下操作:

    df %>%
      group_by(Id) %>%
      mutate(row = paste0("Question1.v", row_number())) %>%
      ungroup() %>%
      spread(row, Question1) %>%
      rename(Question1 = Question1.v1) %>%
      mutate_all(function(x) ifelse(is.na(x), "missing", x))
    
    # # A tibble: 4 x 3
    #      Id Question1 Question1.v2
    #   <int>     <int>        <chr>
    # 1     1         5            3
    # 2     2         3      missing
    # 3     3         5      missing
    # 4     4         1      missing
    

    【讨论】:

    • 快 8 秒 :)
    • :-D 保留你的答案。你有一个稍微替代的方法,使用complete
    • 无需粘贴............将其保存为具有特定名称的数据框并使用该名称而不是我正在使用的df
    【解决方案2】:

    使用数据表包可以做到以下几点:

    library(data.table)
    dat1 <- data.table(Id = c(1, 1, 2, 3, 4), Question1 = c(5, 3, 3, 5, 1))
    

    在您的情况下,如果您有数据框 df1,您应该首先使用 setDT(df1) 将其转换为数据表。

    dat1[, temp := paste0("Question1.V", 1:.N), by = Id]
    res <- dcast(dat1, Id ~ temp, value.var = "Question1")
    names(res)[2] <- "Question1"
    
    > res
       Id Question1 Question1.V2
    1:  1         5            3
    2:  2         3           NA
    3:  3         5           NA
    4:  4         1           NA
    

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 2017-06-16
      • 2020-05-11
      • 1970-01-01
      相关资源
      最近更新 更多