user2418838
user2418838

Reputation: 381

r two dataframe merge by absolute value of one column

I have two dataframes with same format looking like this:

df1)

name value score
 a     2    0.01
 b     2    2.25
 c     1    5.24

df2)

name value score
 A     2    -8.01
 B     2    -3.25
 C     1    -2.24

I want to merge these two list according to the absolute value of "score" column

output)

name value score
 A     2    -8.01
 c     1    5.24
 B     2    -3.25
 b     2    2.25
 C     1    -2.24
 a     2    0.01

Would there be a simple r code for this? I would appreciate any help. Thanks

Upvotes: 2

Views: 416

Answers (1)

thelatemail
thelatemail

Reputation: 93833

rbind and order rows:

newdat <- rbind(dat1,dat2)
newdat[order(abs(newdat$score),decreasing=TRUE),]

#  name value score
#4    A     2 -8.01
#3    c     1  5.24
#5    B     2 -3.25
#2    b     2  2.25
#6    C     1 -2.24
#1    a     2  0.01

Upvotes: 3

Related Questions