Set column values ​​based on another column

I have a dataframe that 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 in a different order).

Desired output:

  ID    Score New.ID New.Score
  123     5      456         1
  456     1      789         0
  789     0      123         5

      

Code to restore 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 use the function for each group. The identifier 123

has a grade 5

in group 1, but it has a grade in group 2 1

. And I just want to use the grades that appear in 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 this 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)

      

+3


source to share


1 answer


A simple one match

must do the trick. Using the data provided:

data <- data.frame(ID, Score, New.ID)
data$New.Score <- data[match(data$New.ID,data$ID),"Score"]

      



And then, checking that this is our desired result:

identical(dt,data)
#[1] TRUE

      

+4


source







All Articles