我想将dataframe
转换为m x n
表。
编写代码并查看原始数据的简化版本,如下所示:
set.seed(1)
dat <- data.frame(x = rep(c("A","B","C","D","E"),2),
y = c("R","S",rep(c("P","Q","R","S"),2)),
val = sample(2:20,10))
x y val
1 A R 7
2 B S 8
3 C P 11
4 D Q 16
5 E R 5
6 A S 14
7 B P 15
8 C Q 9
9 D R 19
10 E S 2
所需结果的代码:
dat2 <- data.frame(x=c("A","B","C","D","E"),
P=c(NA,15,11,NA,NA),
Q=c(NA,NA,9,16,NA),
R=c(7,NA,NA,19,5),
S=c(14,8,NA,NA,2)
)
x P Q R S
1 A NA NA 7 14
2 B 15 NA NA 8
3 C 11 9 NA NA
4 D NA 16 19 NA
5 E NA NA 5 2
因此,基本上,我想将y
中的所有唯一值转换为列,并添加val
中的相应值,从而得到一个5x4矩阵。
答案 0 :(得分:2)
您可以使用dcast()
中的data.table
:
library(data.table)
set.seed(1)
dat <- data.frame(x = rep(c("A","B","C","D","E"),2),
y = c("R","S",rep(c("P","Q","R","S"),2)),
val = sample(2:20,10))
dcast(dat, x ~ y, value.var = "val")
x P Q R S
1 A NA NA 7 14
2 B 15 NA NA 8
3 C 11 9 NA NA
4 D NA 16 19 NA
5 E NA NA 5 2