【问题标题】:cbind two data frames with different rownames and numbers of rowscbind 两个具有不同行名和行数的数据框
【发布时间】:2011-07-19 21:36:17
【问题描述】:

假设我有两个数据框,每个数据框都有不同的行数和列数,并且共享一些行名,但不共享其他行名。我希望能够将它们 cbind 在一起,以便生成的数据帧具有来自组成数据帧的所有唯一行名,并简单地在组成数据中不存在行和列组合的地方放置一个“NA” .我认为必须有某种加入或合并操作可以做到这一点,但我没有成功找到一个。提前致谢!

编辑:这是我写的,它似乎有效,但我不确定它有多强大:

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)
}

【问题讨论】:

  • 不要将数据存储在行名中。使用合并。

标签: r join merge bind dataframe


【解决方案1】:

您的问题对于您想要的结果不够具体(在行名相等的情况下您想要什么?)。我认为您不能使用 rowname 加入 - 只需尝试将 rowname 作为列,然后使用参数 'by' 设置为该列的 merge() 函数。在您的情况下,可能是完全外连接(?),即 all = TRUE?

【讨论】:

  • 如果行名相等,那么我只希望它将两个帧 cbind 在一起。我最终写了一些可以做到这一点的东西,但它很笨重,我不确定它到底有多强大。
  • 直觉上它帮助了我
猜你喜欢
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 2019-10-29
  • 2017-01-01
  • 2020-12-04
  • 2021-12-04
相关资源
最近更新 更多