将具有相同列名的两个数据帧组合在一起

时间:2013-11-19 20:21:31

标签: r dataframe

我有两个带有此格式的data.frame(这是数据集的一小部分):

data.frame 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

data.frame 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 个答案:

答案 0 :(得分:22)

我们可以使用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