如何将这种长格式数据帧转换为宽格式?

时间:2019-03-24 06:14:17

标签: r tidyr

我正在RStudio中使用R进行数据分析。我目前有一个dataframe中的long format。我想将其转换为wide format

dataframedf1)的摘录如下所示。我已经将第一列转换为factor

提取:

df1 <- read.csv("test1.csv", stringsAsFactors = FALSE, header = TRUE)

df1$Respondent <- factor(df1$Respondent)

df1

      Respondent  Question      CS             Imp     LOS  Type  Hotel
1          1       Q1       Fully Applied     High     12   SML   ABC
2          1       Q2       Optimized         Critical 12   SML   ABC

我希望新的dataframe(例如df2)看起来像这样:

Respondent      Q1CS           Q1Imp     Q2CS        Q2Imp     LOS   Type   Hotel
  1          Fully Applied      High    Optimized    Critical   12   SML    ABC

如何在R中做到这一点?

其他说明:我曾尝试查看tidyr软件包及其spread()函数,但是对于解决这个特定问题我很难。

2 个答案:

答案 0 :(得分:1)

这可以通过gather-unite-spread方法实现

df %>%
    group_by(Respondent) %>%
    gather(k, v, CS, Imp) %>%
    unite(col, Question, k, sep = "") %>%
    spread(col, v)
#  Respondent LOS Type Hotel          Q1CS Q1Imp      Q2CS    Q2Imp
#1          1  12  SML   ABC Fully Applied  High Optimized Critical

样本数据

df <- read.table(text =
    "      Respondent  Question      CS             Imp     LOS  Type  Hotel
1          1       Q1       'Fully Applied'     High     12   SML   ABC
2          1       Q2       'Optimized'         Critical 12   SML   ABC", header = T)

答案 1 :(得分:1)

在data.table中,这可以单行完成。...

dcast(DT, Respondent ~ Question, value.var = c("CS", "Imp"), sep = "")[DT, `:=`(LOS = i.LOS, Type = i.Type, Hotel = i.Hotel), on = "Respondent"][]
   Respondent          CSQ1      CSQ2 ImpQ1    ImpQ2 LOS Type Hotel
1:          1 Fully Applied Optimized  High Critical  12  SML   ABC

逐步解释

创建样本数据

DT <- fread("Respondent  Question      CS             Imp     LOS  Type  Hotel
             1  Q1       'Fully Applied'     High     12   SML   ABC
            1   Q2       'Optimized'         Critical 12   SML   ABC", quote = '\'')

按问题将数据表的一部分转换为所需格式
名称可能不是您想要的...您可以随时使用setnames()更改它们。

dcast(DT, Respondent ~ Question, value.var = c("CS", "Imp"), sep = "")
#    Respondent          CSQ1      CSQ2 ImpQ1    ImpQ2
# 1:          1 Fully Applied Optimized  High Critical

然后通过原始DT上的引用进行连接,以获取您需要的其余列...

result.from.dcast[DT, `:=`( LOS = i.LOS, Type = i.Type, Hotel = i.Hotel), on = "Respondent"]