cbind两个具有不同rownames和行数的数据帧 [英] cbind two data frames with different rownames and numbers of rows
问题描述
编辑:这是我写的,似乎有效,但我不确定它是多么强大:
new.cbind< - function(...)
{
input< - eval(substitute(list ),env = parent.frame())
names.orig< - NULL
nrows< - numeric()
for(i in 1:length )
{
nrows [i]< - nrow(input [[i]])
names.orig< - c(names.orig,colnames(input [[i] ]))
}
idx< - (1:length(input))[order(nrows,decrement = 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)
}
你的问题对于你想要的结果不够具体(在这种情况下,你想要的是什么?我认为你不能使用rowname加入 - 只是尝试把rowname作为列,然后使用merge()函数和参数'by'设置到该列。在你的情况下,可能是全外连接(?),即全= TRUE?
Suppose I have two data frames, each with a different number of rows and columns and sharing some row names but not others. 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?
这篇关于cbind两个具有不同rownames和行数的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!