R:将行转换为列并使用 N/A 来获取缺失值

R: Pivot the rows into columns and use N/A's for missing values

我有一个看起来像这样的数据框

NUM <- c("45", "45", "45", "45", "48", "50", "66", "66", "66", "68")
Type <- c("A", "F", "C", "B", "D", "A", "E", "C", "F", "D")
Points <- c(9.2,60.8,22.9,1012.7,18.7,11.1,67.2,63.1,16.7,58.4)

df1 <- data.frame(NUM,Type,Points)

df1:

+-----+------+--------+
| NUM | TYPE | Points |
+-----+------+--------+
|  45 | A    | 9.2    |
|  45 | F    | 60.8   |
|  45 | C    | 22.9   |
|  45 | B    | 1012.7 |
|  48 | D    | 18.7   |
|  50 | A    | 11.1   |
|  66 | E    | 67.2   |
|  66 | C    | 63.1   |
|  66 | F    | 16.7   |
|  65 | D    | 58.4   |
+-----+------+--------+

我正在尝试获取一个输出,该输出将类型列中的行转换为单独的列。

期望的输出:

+-----+----------+----------+----------+----------+----------+----------+
| NUM | Points.A | Points.B | Points.C | Points.D | Points.E | Points.F |
+-----+----------+----------+----------+----------+----------+----------+
|  45 | 9.2      | 1012.7   | 22.9     | N/A      | N/A      | 60.8     |
|  48 | N/A      | N/A      | N/A      | 18.7     | N/A      | N/A      |
|  50 | 11.1     | N/A      | N/A      | N/A      | N/A      | N/A      |
|  66 | N/A      | N/A      | 63.1     | N/A      | 67.2     | 16.7     |
|  65 | N/A      | N/A      | N/A      | N/A      | 58.4     | N/A      |
+-----+----------+----------+----------+----------+----------+----------+

我尝试使用 melt(df1) 但操作错误,因为行中的值是 NUM 值而不是点。请让我知道如何解决这个问题。

你可以试试dcast

library(reshape2)
dcast(df1, NUM~paste0('Points.',Type), value.var='Points')

或者您可以转换为 data.table 并使用 data.table 中的 dcast。会更快

library(data.table)#v1.9.5+
dcast(setDT(df1), NUM~paste0('Points.',Type), value.var='Points')

您正在寻找一个基本的 "long" 到 "wide" 整形过程。

在 base R 中,您可以使用臭名昭著的 reshape。对于这种类型的数据,语法非常简单:

reshape(df1, direction = "wide", idvar = "NUM", timevar = "Type")
#    NUM Points.A Points.F Points.C Points.B Points.D Points.E
# 1   45      9.2     60.8     22.9   1012.7       NA       NA
# 5   48       NA       NA       NA       NA     18.7       NA
# 6   50     11.1       NA       NA       NA       NA       NA
# 7   66       NA     16.7     63.1       NA       NA     67.2
# 10  68       NA       NA       NA       NA     58.4       NA

您也可以使用 "tidyr" 包,因为一些函数只是包装 reshape2 但使用不同的语法。在这种情况下,语法为:

> library(tidyr)
> spread(df1, Type, Points)