Transform a pairwise set of values into a matrix

戏子无情 提交于 2021-02-10 19:41:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!