合并(rbind)数据帧并使用原始数据帧的名称创建列

合并(rbind)数据帧并使用原始数据帧的名称创建列

我有几个数据框,我想按行组合。在生成的单个数据框中,我想创建一个新变量,用于标识观察来自哪个数据集。


# original data frames

df1 <- data.frame(x = c(1, 3), y = c(2, 4))

df2 <- data.frame(x = c(5, 7), y = c(6, 8))


# desired, combined data frame

df3  <- data.frame(x = c(1, 3, 5, 7), y = c(2, 4, 6, 8),

                   source = c("df1", "df1", "df2", "df2")

# x y source

# 1 2    df1

# 3 4    df1

# 5 6    df2

# 7 8    df2

我怎样才能做到这一点?提前致谢!


宝慕林4294392
浏览 722回答 3
3回答

jeck猫

另一种方法dplyr:df1 <- data.frame(x = c(1,3), y = c(2,4))df2 <- data.frame(x = c(5,7), y = c(6,8))df3 <- dplyr::bind_rows(list(df1=df1, df2=df2), .id = 'source')df3Source: local data frame [4 x 3]&nbsp; source&nbsp; &nbsp; &nbsp;x&nbsp; &nbsp; &nbsp;y&nbsp; &nbsp;(chr) (dbl) (dbl)1&nbsp; &nbsp; df1&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;22&nbsp; &nbsp; df1&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;43&nbsp; &nbsp; df2&nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; &nbsp;64&nbsp; &nbsp; df2&nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; &nbsp;8
打开App,查看更多内容
随时随地看视频慕课网APP