开发者

cbind two data frames with different rownames and numbers of rows

开发者 https://www.devze.com 2023-03-21 18:28 出处:网络
Suppose I have two data frames, each with a different number of rows and columns and sharing some row names but not othe开发者_开发知识库rs. I\'d like to be able to cbind them together so that the res

Suppose I have two data frames, each with a different number of rows and columns and sharing some row names but not othe开发者_开发知识库rs. I'd like to be able to cbind them together so that the resultant data frame has all of the unique rownames from from the constituent data frames, and simply puts an 'NA' where the row and column combination did not exist in the constituent data. I thought that there must be some kind of join or merge operation that can do this but I haven't been successful in finding one. Thanks in advance!

Edit: Here's what I wrote and it seems to work, but I'm not sure how robust it is:

new.cbind <- function(...)
{
  input <- eval(substitute(list(...), env = parent.frame()))

  names.orig <- NULL
  nrows <- numeric()
  for (i in 1:length(input))
    {
      nrows[i] <- nrow(input[[i]])
      names.orig <- c(names.orig, colnames(input[[i]])) 
    }

  idx <- (1:length(input))[order(nrows, decreasing=T)]
  x <- NULL
  for (i in 1:length(input))
    {
      x <- c(x, rownames(input[[idx[i]]]))
    }

  r <- data.frame(row.names=unique(x))
  for (i in 1:length(input))
    {
      r <- cbind(r, data.frame(input[[i]][match(rownames(r), rownames(input[[i]])),]))
    }

  colnames(r) <- names.orig

  return(r)
}


Your question is not specific enough about what you want as a result (what you want in the case the rownames are equal?). I think you can't join using rowname - just try to put the rowname as a column and then use merge() function with parameter 'by' set to that column. In your case maybe as full outer join (?) i.e. with all = TRUE?

0

精彩评论

暂无评论...
验证码 换一张
取 消