I have a dataframe with three variables: ID
, group
, and nominated_ID
.
I want to know the group
that nominated_ID
belongs in.
I'm imagining that for each case, we take nominated_ID
, find the case where it is equal to ID
, and then set the nominated_Group
variable in the original case equal to the group
variable in the matched case. (If there is no match, set it to NA)
I wouldn't be surprised if this can be done without a loop, so I'm open-minded about the solution. Thanks so much for your help. Know that I did try to look for similar questions before posting.
You can achieve this in one step without the use of
cbind
by directly allocating results to a column in your data.frame:I used
with
as a convenient way of referring to the columns of df without having to repeatedly writedf$
.The following seems to work; there may be better ways
You can do this in a syntactically compact way using
transform
,match
and array indexing. Using @Henry's data-frame:Probably not the most "intuitive' way, but merging
df
againstdf
also works if you use nominated_ID as the merge index for the first copy and ID as the by index for the second and keep all rows. You need to drop the secondnominated_ID
column and rearrange the order to get things to match the answers above: