将具有相同列名的两个数据框合并

24

我有两个数据框,格式如下(这是数据集的一小部分):

数据框1

ID  precip  lat lon
1   45  115 -122.5
2   42.5    130 -122.5
3   40  155 -122.5
4   37.5    140 -122.5

数据框 2

    precip  lat lon
1   108.61  115 -122.5
2   85.83   130 -122.5
3   81.01   155 -122.5
4   NA  140 -122.5

我想将 data.frame2 添加到 data.frame1 的末尾,以便最终得到以下结果:

ID  precip  lat lon
1   45  115 -122.5
2   42.5    130 -122.5
3   40  155 -122.5
4   37.5    140 -122.5
5   108.61  115 -122.5
6   85.83   130 -122.5
7   81.01   155 -122.5
8   NA  140 -122.5
1个回答

40

我们可以使用rbind

cbind, rbind: 将一系列向量、矩阵或数据框按列或行组合。

# dataframe 1
df1 <- read.table(text = "
ID  precip  lat lon
1   45  115 -122.5
2   42.5    130 -122.5
3   40  155 -122.5
4   37.5    140 -122.5
", header = TRUE)
# dataframe 2
df2 <- read.table(text = "
ID precip  lat lon
1   108.61  115 -122.5
2   85.83   130 -122.5
3   81.01   155 -122.5
4   NA  140 -122.5
", header = TRUE)

# combine by row
df3 <- rbind(df1, df2)

# update ID column
df3$ID <- 1:nrow(df3)

# output
df3
#   ID precip lat    lon
# 1  1  45.00 115 -122.5
# 2  2  42.50 130 -122.5
# 3  3  40.00 155 -122.5
# 4  4  37.50 140 -122.5
# 5  5 108.61 115 -122.5
# 6  6  85.83 130 -122.5
# 7  7  81.01 155 -122.5
# 8  8     NA 140 -122.5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接