Reputation: 133
Suppose I have two data frames, df and df2, that look like:
df
User Lab Score
A 1021 12
A 1022 10
A 1024 15
B 1021 9
B 1022 9
B 1023 14
C 1024 10
df2
Lab Score
1021 15
1022 10
1023 15
1024 15
I want to divide the Score column in df by the Score column in df2, depending on the Lab. Therefore I want to end up with a data frame that looks like:
User Lab Score
A 1021 0.8
A 1022 1.0
A 1024 1.0
B 1021 0.6
B 1022 0.9
B 1023 0.93
C 1024 0.67
where 12/15 = 0.8, 10/10 = 1.0, 15/15 = 1.0,9/15 = 0.6, 9/10 = 0.9, 14/15 = 0.9333, 10/15 = 0.6667
Upvotes: 0
Views: 1236
Reputation: 59970
Just match the Labs up like this:
df$Score <- df$Score / df2$Score[ match( df$Lab , df2$Lab ) ]
# User Lab Score
#1 A 1021 0.8000000
#2 A 1022 1.0000000
#3 A 1024 1.0000000
#4 B 1021 0.6000000
#5 B 1022 0.9000000
#6 B 1023 0.9333333
#7 C 1024 0.6666667
match
returns the index of the first match of it's first argument in it's second argument. In English it returns which row in df2
is the match for each Lab in df
.
Upvotes: 1