R: matrix fusion (not data.frames)

merge is a very nice feature: it combines matrices and data.frames and returns data.frame.

Having fairly large character matrices, is there another good way to merge - without converting data.frame?


Comment 1: A small function for merging a named vector with a matrix or data.frame. Elements of a vector can refer to several entries in a matrix:

expand <- function(v,m,by.m,v.name='v',...) {
  df <- do.call(rbind,lapply(names(v),function(x) {
    pos <- which(m[,by.m] %in% v[x])
    cbind(x,m[pos,],...)
  }))
  colnames(df)[1] <- v.name
  df
}

Example:

v <- rep(letters,each=3)[seq_along(letters)]
names(v) <- letters
m <- data.frame(a=unique(v),b=seq_along(unique(v)),stringsAsFactors=F)
expand(v,m,'a')
+3
source share
3 answers

You can use a combination of match and cbind to perform the merge equivalent without converting to a data frame, a simple example:

st1 <- state.x77[ sample(1:50), ]
st2 <- as.matrix( USArrests )[ sample(1:50), ]

tmp1 <- match(rownames(st1), rownames(st2) )

st3 <- cbind( st1, st2[tmp1,] )
head(st3)

Keeping track of the columns you want and merging with many of the 1 relationships or missing rows in the same group requires a little more thought, but is still possible.

+8

, (a) (b) merge.matrix() S3 ( ).

merge:

.

, merge.default:

> merge.default
function (x, y, ...) 
merge(as.data.frame(x), as.data.frame(y), ...)
+3

Matrix.utils merge.Matrix. , M Matrices, data.frames ..

, , -, m: n . merge, all.x, all.y ..

+2

Source: https://habr.com/ru/post/1764884/


All Articles