Marta
Marta

Reputation: 85

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.

Upvotes: 4

Views: 2372

Answers (2)

Dominic Comtois
Dominic Comtois

Reputation: 10431

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

Upvotes: 3

zx8754
zx8754

Reputation: 56259

In case d1 and d2 have different number of rows:

chosen <- numeric(length = nrow(d1))
choices <- paste(d1$A, d1$B)

for(i in seq(nrow(d1))){
  chosen[i] <- match(paste(d2$A[i], d2$B[i]), choices)
  choices[chosen] <- 0
  }

d2$Y <- d1[chosen, "Y"]
d2$Y
#[1]  4  5  3  2 11  9 10  8

Upvotes: 0

Related Questions