gpt4 book ai didi

r - 合并两个列名相同的数据框

转载 作者:行者123 更新时间:2023-12-04 00:19:25 28 4
gpt4 key购买 nike

我有两个这种格式的 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

数据框 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

最佳答案

我们可以使用 rbind :

cbind, rbind: Take a sequence of vector, matrix or data-frame arguments and combine by columns or rows, respectively.


# 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

关于r - 合并两个列名相同的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20081256/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com