Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a data.frame with columns of another data.frame

I have the folowing data.frames:

d1 <- data.frame(A=c(-1,-1,1,1,-1,-1,1,1), B=c(-1,1,-1,1,-1,1,1,-1), Y=c(2,3,4,5,8,9,10,11))
d2 <- data.frame(A=c(1,1,-1,-1,1,-1,1,-1), B=c(-1,1,1,-1,-1,1,1,-1))

I would like to add the column Y to the d2 data.frame. I've tried using merge function, but then I duplicate the number of rows of the data.frame.

I've also tried to use the functions order and match to order the first data.frame by the columns of the second one:

d1[order(match(
  paste(d1$A,d1$B),
  paste(d2df$A,d2df$B))
),]

But it doesn't work and I don't know why.

like image 288
Marta Avatar asked Sep 02 '25 04:09

Marta


1 Answers

If I understand correctly, this would give you the results you're after:

# Sort d1 and d2 with columns A and B
d1 <- d1[order(d1$A,d1$B),]
d2 <- d2[order(d2$A,d2$B),]

# Copy Y from d1 to d2
d2$Y <- d1$Y

# Restore original order in d1 and d2
d1 <- d1[order(rownames(d1)),]
d2 <- d2[order(rownames(d2)),]

d2$Y
#[1]  4  5  3  2 11  9 10  8
like image 165
Dominic Comtois Avatar answered Sep 05 '25 00:09

Dominic Comtois