dataframe - Divide a Column based on two Data Frames in R -


suppose have 2 data frames, df , df2, like:

df

        user    lab    score               1021    12               1022    10               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 divide score column in df score column in df2, depending on lab. therefore want end data frame looks like:

        user    lab    score               1021   0.8               1022   1.0               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

just match labs this:

df$score <- df$score / df2$score[ match( df$lab , df2$lab ) ] #  user  lab     score #1    1021 0.8000000 #2    1022 1.0000000 #3    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 index of first match of it's first argument in it's second argument. in english returns row in df2 match each lab in df.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -