Lookup value from another column that matches with variable

后端 未结 3 1586
-上瘾入骨i
-上瘾入骨i 2021-01-21 01:12

I have a dataframe that looks like:

animal_id   trait_id    sire_id dam_id
    1         25.05        0       0
    2         -46.3        1       2
    3                


        
3条回答
  •  被撕碎了的回忆
    2021-01-21 01:30

    You can use match; match(col, df$animal_id) gives corresponding index of elements from col in the animal_id, which can be used further to locate the values of trait:

    df[c("trait_sire", "trait_dam")] <- 
        lapply(df[c("sire_id", "dam_id")], function(col) df$trait_id[match(col, df$animal_id)])
    
    df
    #  animal_id trait_id sire_id dam_id trait_sire trait_dam
    #1         1    25.05       0      0         NA        NA
    #2         2   -46.30       1      2      25.05    -46.30
    #3         3    41.60       1      2      25.05    -46.30
    #4         4   -42.76       3      4      41.60    -42.76
    #5         5   -10.99       3      4      41.60    -42.76
    #6         6   -49.81       5      4     -10.99    -42.76
    

提交回复
热议问题