如何在不更改顺序的情况下合并具有相同行名(和列名)的多个数据框?

时间:2017-03-03 23:26:27

标签: r dataframe

##Make up 3 data frames 

Var<- c("t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11")
res <- c(2,3.1,4.5,5.1,6.5,7.1,8.5,9.11,10.1,11.8,12.3) 
df_1 <- data.frame(res,Var)

Var<- c("t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11")
res <- c(2.2,3.3,4.5,5.1,6.5,13,0,0,10.1,1,12.3) 
df_2 <- data.frame(res,Var)

Var<- c("t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11")
res <- c(0,3.3,0,5.1,6.5,13,0,1,10.1,1,1) 
df_3 <- data.frame(res,Var)

merged_df<- Reduce(function(...) merge(..., all=TRUE), list(df_1,df_2,df_3))

这里的问题是我希望“merged_df”的行为“t1”为df_1,然后是“t1”的df_2,然后是“t1”的df_3,依此类推,但上面的函数会根据值对它们进行排序!

知道如何克服这个问题吗? 感谢

1 个答案:

答案 0 :(得分:3)

# assign grp variables
df_1$grp <- 'df_1'  
df_2$grp <- 'df_2'
df_3$grp <- 'df_3'

# merge data frames
long_df <- do.call('rbind', list(df_1, df_2, df_3))

# output
head( long_df )
#   res Var  grp
# 1 2.0  t1 df_1
# 2 3.1  t2 df_1
# 3 4.5  t3 df_1
# 4 5.1  t4 df_1
# 5 6.5  t5 df_1
# 6 7.1  t6 df_1

对列Var

进行排序
long_df <- within( long_df, Var <- factor( Var, 
                                           levels = c("t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11"),
                                           ordered = TRUE ))

sort_long_df <- with( long_df, long_df[ order(Var), ])
head(sort_long_df, 10)
#    res Var  grp
# 1  2.0  t1 df_1
# 12 2.2  t1 df_2
# 23 0.0  t1 df_3
# 2  3.1  t2 df_1
# 13 3.3  t2 df_2
# 24 3.3  t2 df_3
# 3  4.5  t3 df_1
# 14 4.5  t3 df_2
# 25 0.0  t3 df_3
# 4  5.1  t4 df_1