rbind数据帧,重复的行名问题 [英] rbind data frames, duplicated rownames issue
问题描述
matrix
中允许使用重复的行(和列)名称,但data.frame
中不允许使用重复的行(和列)名称.尝试rbind()
某些具有共同行名的数据框突出了此问题.考虑下面的两个数据帧:
While duplicated row (and column) names are allowed in a matrix
, they are not allowed in a data.frame
. Trying to rbind()
some data frames having row names in common highlights this problem. Consider two data frames below:
foo = data.frame(a=1:3, b=5:7)
rownames(foo)=c("w","x","y")
bar = data.frame(a=c(2,4), b=c(6,8))
rownames(bar)=c("x","z")
# foo bar
# a b a b
# w 1 5 x 2 6
# x 2 6 y 4 8
# y 3 7
现在尝试rbind()
它们(请注意行名):
Now trying to rbind()
them (Pay attention to the row names):
rbind(foo, bar)
# a b
# w 1 5
# x 2 6
# y 3 7
# x1 2 6
# z 4 8
但对于matrix
:
rbind(as.matrix(foo), as.matrix(bar))
# a b
# w 1 5
# x 2 6
# y 3 7
# x 2 6
# z 4 8
这是问题所在:如何rbind()
删除两个重复行(具有相同行名)的数据帧?
Here is the problem: How to rbind()
two data frames, having duplicated rows (with the same row name) removed?
推荐答案
如何
duprows <- which(!is.na(match(rownames(bar),rownames(foo))))
rbind(foo,bar[-duprows,])
?
或(基于以下评论)
duprows <- rownames(bar) %in% rownames(foo)
rbind(foo, bar[!duprows,])
根据(1)选择匹配或不匹配,可能会出现多种变化; (2)查找匹配的数字或逻辑值.
Several variations are possible depending on (1) selected matched or unmatched; (2) finding numeric or logical values for the matches.
这篇关于rbind数据帧,重复的行名问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!