我有2个数据框,我尝试merge
使用row.names
:
df1 <- data.frame(col11=c('v111', 'v112', 'v113'),
col12=c('v121', 'v122', 'v123'),
col13=c('v131', 'v132', 'v133'))
row.names(df1) <- c('rec1', 'rec2', 'rec3')
# col11 col12 col13
# rec1 v111 v121 v131
# rec2 v112 v122 v132
# rec3 v113 v123 v133
df2 <- data.frame(col21=c('v213', 'v214'),
col22=c('v223', 'v224'))
row.names(df2) <- c('rec3', 'rec4')
# col21 col22
# rec3 v213 v223
# rec4 v214 v224
dfM <- merge(x = df1, y = df2, by = 'row.names', all = T)
# Row.names col11 col12 col13 col21 col22
# 1 rec1 v111 v121 v131 <NA> <NA>
# 2 rec2 v112 v122 v132 <NA> <NA>
# 3 rec3 v113 v123 v133 v213 v223
# 4 rec4 <NA> <NA> <NA> v214 v224
问题在于,生成的data.frame row.names
会转换为其他列Row.names
,即我必须运行row.names(dfM) <- dfM$Row.names; dfM$Row.names <- NULL;
之类的内容。有什么方法可以避免这种情况吗?
P.S。我想避免这种情况,因为事实上我不仅合并了2个数据帧,而且合并在一个列表中:
df_list <- list(df1, df2) # in fact my list contains many dataframes
dfM <- Reduce(function(x,y){merge(x, y, by='row.names', all=T)}, df_list)
解决出现Row.names的问题,现在我必须以这种方式调用Reduce
:
dfM <- Reduce(function(x,y){df <- merge(x, y, by='row.names', all=T);
row.names(df) <- df$Row.names;
df$Row.names <- NULL;
df;
}, nrm_plates)
我只是想知道是否有更优雅的解决方案......