I have a data frame which looks like this:
ID Score New.ID New.Score
123 5 456
456 1 789
789 0 123
I would like to give the same scores to the New.ID column (which are just in a different order).
Desired result:
ID Score New.ID New.Score
123 5 456 1
456 1 789 0
789 0 123 5
Code to reconstruct data frame:
ID <- as.factor(c(123,456,789))
Score <- c(5,1,0)
New.ID<- as.factor(c(456, 789, 123))
New.Score <- c(1,0,5)
dt <- data.frame(ID, Score, New.ID, New.Score)
Update
Desired output:
Group ID Score New.ID New.Score
1 123 5 456 1
1 456 1 789 0
1 789 0 123 5
2 555 1 999 0
2 123 1 123 1
2 999 0 555 1
So I am trying to attempt to use the function for each group. The ID 123
has score 5
in group 1, but in group 2 it has score 1
. And I only want to use the scores that appear within each group.
I tried with ave
:
mtch <- function(x) {
dt[match(x,dt$ID),"Score"]
}
dt$New.Score <- ave(dt$New.ID, dt$Group, FUN = mtch)
But it gives me NA values.
Code for second df:
Group <- as.factor(c(1, 1, 1, 2, 2, 2))
ID <- as.factor(c(123,456,789, 555, 123, 999))
Score <- c(5,1,0, 1,1,0)
dt <- data.frame(Group, ID, Score, New.ID)
A simple match
should do the trick. Using the data you provided:
data <- data.frame(ID, Score, New.ID)
data$New.Score <- data[match(data$New.ID,data$ID),"Score"]
And then checking that it's our desired result:
identical(dt,data)
#[1] TRUE
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments