Home > Enterprise >  Is there a R function to return a row value based on column?
Is there a R function to return a row value based on column?

Time:10-01

Is there a R function to return the value for name 2 in score 2? For example, I want Bob's score in the score 2 slot for Joe by getting Bob's score from the third row. Any help would be much appreciated. If this question has already been answered, happy to look at other answers.

Name Score Name 2 Score 2
Joe 100 Bob
Mary 95 Joe
Bob 60 Mary

CodePudding user response:

We may use match to get the index and use that to return the 'Score'

df1$Score2 <- with(df1, Score[match(Name2, Name)])

-output

> df1
  Name Score Name2 Score2
1  Joe   100   Bob     60
2 Mary    95   Joe    100
3  Bob    60  Mary     95

data

df1 <- structure(list(Name = c("Joe", "Mary", "Bob"), Score = c(100, 
95, 60), Name2 = c("Bob", "Joe", "Mary")),
 class = "data.frame", row.names = c(NA, 
-3L))
  •  Tags:  
  • r
  • Related