如何通过省略缺失值将水平数据集重组为垂直数据集

时间:2019-09-10 16:14:54

标签: r

我的数据框数据如下所示:

Dim i As Integer
For i = 1 To wkbook.Worksheets("T").Range("TEAMS").Rows.Count
  With wkbook.Worksheets("T").Range("TEAMS[D]")(i)
    If .Value2 <> department Then
      .EntireRow.Delete
    End If
  End With
Next i

我想使它像下面这样:

PatID     X1       X2     X3     X4     X5    X6      X7       X8
  1       0.8288 0.7920 0.7552 0.6447   NA    NA      NA       NA
  2       0.9500 0.9500 0.9500 0.9139 0.8092  NA      NA       NA
  3        NA      NA     NA     NA     NA    NA      NA       NA
  4        0.9500 0.9100  0.8092 NA     NA    NA      NA       NA

1 个答案:

答案 0 :(得分:0)

您可以在melt中尝试reshape2

new_df <- melt(df, id.vars = 'PatID', na.rm = TRUE)
new_df[order(new_df$PatID),]

输出:

   PatID variable  value
1      1       X1 0.8288
5      1       X2 0.7920
9      1       X3 0.7552
13     1       X4 0.6447
2      2       X1 0.9500
6      2       X2 0.9500
10     2       X3 0.9500
14     2       X4 0.9139
18     2       X5 0.8092
4      4       X1 0.9500
8      4       X2 0.9100
12     4       X3 0.8092