逐行比较两个数据帧,并在每次不相等时添加一行

时间:2022-11-15 20:11:55

I'm trying to compare two dataframes row by row, let's say df1 with 4 rows and df2 with 3 rows :

我试图逐行比较两个数据帧,让我们说df1有4行,df2有3行:

df1 <- data.frame(x1=c('a','b','c','d'),x2=c(1,2,3,4))
df2 <- data.frame(x1=c('a','b','d'),x2=c(5,6,7))

I'd like to transform df2 by comparing it with df1 row by row : each time the value of row i in column1 for df2 is different from the value of row i in column1 for df1, I'd like to add a new row in df2 so that at the end of the loop, the two dataframes have the same number of rows and also the first columns are exactly the same.

我想通过逐行比较df1来转换df2:每次df2的column1中的第i行的值与df1的column1中的第i行的值不同时,我想添加一个新行df2使得在循环结束时,两个数据帧具有相同的行数,并且第一列完全相同。

It means that I would like df2 looks like this at the end of the comparison :

这意味着我希望df2在比较结束时看起来像这样:

df2 <- data.frame(x1=c('a','b','c','d'),x2=c(5,6,0,7))

I've tried doing that with a loop but R returns an error

我尝试用循环但是R返回错误

Error in Ops.factor(df1[i, 1], df2[i, 1]) : les niveaux des facteurs diffèrent"

Ops.factor中的错误(df1 [i,1],df2 [i,1]):les niveaux des facteursdiffèrent“

for (i in 1:length(df2)){
  if (df1[i,1]!=df2[i,1])
  {df1<- rbind(df1[1:i,],df2[i,],df1[i+1,])}
}

1 个解决方案

#1


2  

You want to do a left join basically:

你想基本上做一个左连接:

new_df2 <- merge(df1["x1"],df2,all.x=TRUE)

Then if you want 0 instead of NA

然后,如果你想要0而不是NA

new_df2$x2[is.na(new_df2$x2)] <- 0

#   x1 x2
# 1  a  5
# 2  b  6
# 3  c  0
# 4  d  7

#1


2  

You want to do a left join basically:

你想基本上做一个左连接:

new_df2 <- merge(df1["x1"],df2,all.x=TRUE)

Then if you want 0 instead of NA

然后,如果你想要0而不是NA

new_df2$x2[is.na(new_df2$x2)] <- 0

#   x1 x2
# 1  a  5
# 2  b  6
# 3  c  0
# 4  d  7