Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracking what and how oberservations changed between two dataframes

Tags:

r

I have the following data:

x <- c("aaa", "bbb", "ccc", "ddd", "eee")
y <- c(1, 0, 0, 1, 1)
df1 <- data.frame(x,y)
x <- c("aaa", "bbb", "ccc", "ddd", "eee")
y <- c(1, 1, 1, 1, 0)
df2 <- data.frame(x,y)

Structure:

> df1
    x y
1 aaa 1
2 bbb 0
3 ccc 0
4 ddd 1
5 eee 1
> df2
    x y
1 aaa 1
2 bbb 1
3 ccc 1
4 ddd 1
5 eee 0

I'd like to track changes between df1 and df2.

If I anti_join(df2,df1) I can keep the things that have changed:

x   y
eee 0
ccc 1
bbb 1

But I want to know WHAT and HOW things changed from df1 to df2. For example:

x   y.from  y.to
eee 1       0
ccc 0       1
bbb 0       1

Thanks in advance.

like image 752
emehex Avatar asked Jan 28 '26 03:01

emehex


2 Answers

Try this:

#merge on column x
df3 <- merge(df1,df2,by="x")

#show the change
df3[ df3[,2] != df3[,3],]
#     x y.x y.y
# 2 bbb   0   1
# 3 ccc   0   1
# 5 eee   1   0
like image 197
zx8754 Avatar answered Jan 30 '26 20:01

zx8754


You can try

index<-(df1$y!=df2$y)
cbind(df1[index,], df2[index,"y"])
like image 35
C_Z_ Avatar answered Jan 30 '26 20:01

C_Z_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!