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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With