有很多方法可以做到这一点。此答案从迅速成为标准方法的方法开始,但还包括旧方法和各种其他方法,包括对散布在此站点上的类似问题的答案。
tmp <- data.frame(x=gl(2,3, labels=letters[24:25]),
y=gl(3,1,6, labels=letters[1:3]),
z=c(1,2,3,3,3,2))
使用 tidyverse:
使用来自tidyr 1.0.0 的pivot_wider 是一种很酷的新方法。它返回一个数据框,这可能是该答案的大多数读者想要的。但是,对于热图,您需要将其转换为真正的矩阵。
library(tidyr)
pivot_wider(tmp, names_from = y, values_from = z)
## # A tibble: 2 x 4
## x a b c
## <fct> <dbl> <dbl> <dbl>
## 1 x 1 2 3
## 2 y 3 3 2
旧的很酷的新方法是使用来自tidyr 的spread。它同样返回一个数据框。
library(tidyr)
spread(tmp, y, z)
## x a b c
## 1 x 1 2 3
## 2 y 3 3 2
使用 reshape2:
向 tidyverse 迈出的第一步是 reshape2 包。
要获取矩阵,请使用acast:
library(reshape2)
acast(tmp, x~y, value.var="z")
## a b c
## x 1 2 3
## y 3 3 2
或者要获取数据框,请使用dcast,如这里:Reshape data for values in one column。
dcast(tmp, x~y, value.var="z")
## x a b c
## 1 x 1 2 3
## 2 y 3 3 2
使用 plyr:
在 reshape2 和 tidyverse 之间出现了 plyr,带有 daply 函数,如下所示:https://stackoverflow.com/a/7020101/210673
library(plyr)
daply(tmp, .(x, y), function(x) x$z)
## y
## x a b c
## x 1 2 3
## y 3 3 2
使用矩阵索引:
这有点老派,但很好地演示了矩阵索引,在某些情况下非常有用。
with(tmp, {
out <- matrix(nrow=nlevels(x), ncol=nlevels(y),
dimnames=list(levels(x), levels(y)))
out[cbind(x, y)] <- z
out
})
使用xtabs:
xtabs(z~x+y, data=tmp)
使用稀疏矩阵:
Matrix 包中还有 sparseMatrix,如下所示:R - convert BIG table into matrix by column names
with(tmp, sparseMatrix(i = as.numeric(x), j=as.numeric(y), x=z,
dimnames=list(levels(x), levels(y))))
## 2 x 3 sparse Matrix of class "dgCMatrix"
## a b c
## x 1 2 3
## y 3 3 2
使用reshape:
您还可以使用基本 R 函数 reshape,如下所示:Convert table into matrix by column names,但您必须在之后进行一些操作以删除额外的列并正确命名(未显示)。
reshape(tmp, idvar="x", timevar="y", direction="wide")
## x z.a z.b z.c
## 1 x 1 2 3
## 4 y 3 3 2