gpt4 book ai didi

r - 合并两个 data.frames 并用 df2 的值替换 df1 某些列的值

转载 作者:行者123 更新时间:2023-12-04 10:58:23 25 4
gpt4 key购买 nike

我有两个 data.frames,我想合并和替换 df1 某些列的值
df2 的值。在这个工作示例中,只有 3 列。但在原始数据中,
在最终的 data.frame 中应该保留大约 20 列。

NO <- c(2, 4, 7, 18, 25, 36, 48)
WORD <- c("apple", "peach", "plum", "orange", "grape", "berry", "pear")
CLASS <- c("p", "x", "x", "n", "x", "p", "n")
ColA <- c("hot", "warm", "sunny", "rainy", "windy", "cloudy", "snow")
df1 <- data.frame(NO, WORD, CLASS, ColA)
df1

# NO WORD CLASS ColA
# 1 2 apple p hot
# 2 4 peach x warm
# 3 7 plum x sunny
# 4 18 orange n rainy
# 5 25 grape x windy
# 6 36 berry p cloudy
# 7 48 pear n snow

NO <- c(4, 18, 36)
WORD <- c("patricia", "oliver", "bob")
CLASS <- c("p", "n", "x")

df2 <- data.frame(NO, WORD, CLASS)
df2

# NO WORD CLASS
# 1 4 patricia p
# 2 18 oliver n
# 3 36 bob x

我想合并两个 data.frames 并从 df1 替换 WORD 和 CLASS 的值
使用来自 df2 的 WORD 和 CLASS 的值

我的 data.frame 应该是这样的:
#   NO      WORD CLASS   ColA
# 1 2 apple p hot
# 2 4 patricia p warm
# 3 7 plum x sunny
# 4 18 oliver n rainy
# 5 25 grape x windy
# 6 36 bob x cloudy
# 7 48 pear n snow

最佳答案

尝试这个

auxind<-match(df2$NO, df1$NO)  # Stores the repeated rows in df1
dfuni<-(rbind(df1[,1:3],df2)[-auxind,]) # Merges both data.frames and erases the repeated rows from the first three colums of df1
dfuni<-dfuni[order(dfuni$NO),] # Sorts the new data.frame
df1[,1:3]<-dfuni

关于r - 合并两个 data.frames 并用 df2 的值替换 df1 某些列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22283900/

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