问题
I would like to transform the following dataframe in R:
> df <- data.frame(cbind(rep(c("F1","F2","F3"),3), rep(c("F1","F2","F3"),each=3),c(1,2,3,4,5,6,7,8,9)))
into the following matrix:
mat <- matrix(c(1,2,3,4,5,6,7,8,9),nrow=3, dimnames=list(c("F1","F2","F3"), c("F1","F2","F3")))
It seems like apply would be a likely candidate but I can't seem to get the syntax correct.
Thanks very much
回答1:
Try
res <- xtabs(as.numeric(as.character(X3))~., df)
attr(res, 'class') <- NULL
attr(res, 'call') <- NULL
dimnames(res) <- unname(dimnames(res))
res
# F1 F2 F3
#F1 1 4 7
#F2 2 5 8
#F3 3 6 9
Or use acast from reshape2
df$X3 <- as.numeric(as.character(df$X3))
acast(df, X1~X2, value.var='X3')
# F1 F2 F3
#F1 1 4 7
#F2 2 5 8
#F3 3 6 9
回答2:
Or by library(dplyr) and library(tidyr)
# assume df is your data frame
df %>% spread(X2, X3)
# you get
X1 F1 F2 F3
1 F1 1 4 7
2 F2 2 5 8
3 F3 3 6 9
If you use library(tidyr) alone, could do:
spread(df, X2, X3)
来源:https://stackoverflow.com/questions/26953583/transform-a-pairwise-set-of-values-into-a-matrix