将三列数据框重塑为matrix(“长”到“宽”格式)
我有一个data.frame
看起来像这样。
xa 1 xb 2 xc 3 ya 3 yb 3 yc 2
我想要这个matrixforms,所以我可以喂它到热图做一个情节。 结果应该如下所示:
abc x 1 2 3 y 3 3 2
我已经尝试从重塑包转换,我已经尝试编写一个手动function来做到这一点,但我似乎并没有得到正确的。
有很多方法可以做到这一点。 这个答案从我最喜欢的方式开始,但也收集各种方式从答案散落在这个网站周围的类似问题。
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))
使用reshape2:
library(reshape2) acast(tmp, x~y, value.var="z")
使用matrix索引:
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)
您也可以使用reshape
,如下所示: 通过列名将表转换为matrix ,但是之后您必须稍微进行一些操作,以删除多余的列并获取正确的名称(未显示)。
> reshape(tmp, idvar="x", timevar="y", direction="wide") x za zb zc 1 x 1 2 3 4 y 3 3 2
Matrix
包中还有sparseMatrix
,如下所示: R – 将BIG表按列名转换为matrix
> 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" abc x 1 2 3 y 3 3 2
也可以使用plyr
库中的daply
函数,如下所示: https : plyr
> library(plyr) > daply(tmp, .(x, y), function(x) x$z) y xabc x 1 2 3 y 3 3 2
dcast
的dcast也可以工作,如下所示: 为一列中的值 dcast
整形数据 ,但是会得到一个包含x
值的列的data.frame。
> dcast(tmp, x~y, value.var="z") xabc 1 x 1 2 3 2 y 3 3 2
同样,从“tidyr” spread
也将为这样一个转变:
library(tidyr) spread(tmp, y, z) # xabc # 1 x 1 2 3 # 2 y 3 3 2
这个问题已经有几年了,但也许有些人仍然对其他答案感兴趣。
如果你不想加载任何包,你可以使用这个函数:
#' Converts three columns of a data.frame into a matrix -- eg to plot #' the data via image() later on. Two of the columns form the row and #' col dimensions of the matrix. The third column provides values for #' the matrix. #' #' @param data data.frame: input data #' @param rowtitle string: row-dimension; name of the column in data, which distinct values should be used as row names in the output matrix #' @param coltitle string: col-dimension; name of the column in data, which distinct values should be used as column names in the output matrix #' @param datatitle string: name of the column in data, which values should be filled into the output matrix #' @param rowdecreasing logical: should the row names be in ascending (FALSE) or in descending (TRUE) order? #' @param coldecreasing logical: should the col names be in ascending (FALSE) or in descending (TRUE) order? #' @param default_value numeric: default value of matrix entries if no value exists in data.frame for the entries #' @return matrix: matrix containing values of data[[datatitle]] with rownames data[[rowtitle]] and colnames data[coltitle] #' @author Daniel Neumann #' @date 2017-08-29 data.frame2matrix = function(data, rowtitle, coltitle, datatitle, rowdecreasing = FALSE, coldecreasing = FALSE, default_value = NA) { # check, whether titles exist as columns names in the data.frame data if ( (!(rowtitle%in%names(data))) || (!(coltitle%in%names(data))) || (!(datatitle%in%names(data))) ) { stop('data.frame2matrix: bad row-, col-, or datatitle.') } # get number of rows in data ndata = dim(data)[1] # extract rownames and colnames for the matrix from the data.frame rownames = sort(unique(data[[rowtitle]]), decreasing = rowdecreasing) nrows = length(rownames) colnames = sort(unique(data[[coltitle]]), decreasing = coldecreasing) ncols = length(colnames) # initialize the matrix out_matrix = matrix(NA, nrow = nrows, ncol = ncols, dimnames=list(rownames, colnames)) # iterate rows of data for (i1 in 1:ndata) { # get matrix-row and matrix-column indices for the current data-row iR = which(rownames==data[[rowtitle]][i1]) iC = which(colnames==data[[coltitle]][i1]) # throw an error if the matrix entry (iR,iC) is already filled. if (!is.na(out_matrix[iR, iC])) stop('data.frame2matrix: double entry in data.frame') out_matrix[iR, iC] = data[[datatitle]][i1] } # set empty matrix entries to the default value out_matrix[is.na(out_matrix)] = default_value # return matrix return(out_matrix) }
怎么运行的:
myData = as.data.frame(list('dim1'=c('x', 'x', 'x', 'y','y','y'), 'dim2'=c('a','b','c','a','b','c'), 'values'=c(1,2,3,3,3,2))) myMatrix = data.frame2matrix(myData, 'dim1', 'dim2', 'values') myMatrix > abc > x 1 2 3 > y 3 3 2