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
You can do this using match
(in base R) in one run (no need to loop over)
df[c("trait_sire", "trait_dam")] <-
cbind(with(df, trait_id[match(sire_id, animal_id)]),
with(df, trait_id[match(dam_id, animal_id)]))
# 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