Loop to create a new variable based on other cases in R (very simple)

I have dataframe with three variables: ID, groupand nominated_ID. I want to know groupwhich one I belong to nominated_ID.

It seems to me that for each case we take nominated_ID, find the case when it is equal ID, and then set the variable nominated_Groupin the original case, equal to the variable groupin the agreed case. (If there is no match, set it to NA)

I would not be surprised if this can be done without a cycle, so I do not agree with the decision. Many thanks for your help. Know that I tried to look for similar questions before posting.

+3
source share
4

cbind data.frame:

df$nominated_group <- with(df, group[match(nominated_ID, ID)])
df
  ID group nominated_ID nominated_group
1  9   Odd            9             Odd
2  5   Odd            8            <NA>
3  2  Even            4            Even
4  4  Even            9             Odd
5  3   Odd            2            Even

with df df$.

+4

, :

> df <- data.frame(ID = c(9, 5, 2, 4, 3), 
+                  group = c("Odd", "Odd", "Even", "Even", "Odd"),
+                  nominated_ID = c(9, 8, 4, 9, 2)                 )
> df
  ID group nominated_ID
1  9   Odd            9
2  5   Odd            8
3  2  Even            4
4  4  Even            9
5  3   Odd            2
> nominated_Group <- df[match(df$nominated_ID, df$ID), ]$group
> newDF <- cbind(df, nominated_Group)
> newDF
  ID group nominated_ID nominated_Group
1  9   Odd            9             Odd
2  5   Odd            8            <NA>
3  2  Even            4            Even
4  4  Even            9             Odd
5  3   Odd            2            Even
+3

, transform, match . @Henry:

df <- transform( df, nominated_group = group[match(nominated_ID, ID)])

> df
  ID group nominated_ID nominated_group
1  9   Odd            9             Odd
2  5   Odd            8            <NA>
3  2  Even            4            Even
4  4  Even            9             Odd
5  3   Odd            2            Even
+3

This is probably not the most “intuitive” way, but merging dfwith dfalso works if you use nominated_ID as the merge index for the first copy and identifier as the index for the second and keep all the rows. you need to drop the second column nominated_IDand streamline the order in order to get things to fit the answers above:

merge(df,df, by.x=3, by.y=1, all.x=TRUE)[order(df$nominated_ID), c(2,3, 1, 4)]

  ID group.x nominated_ID group.y
5  4    Even            9     Odd
3  5     Odd            8    <NA>
2  2    Even            4    Even
1  3     Odd            2    Even
4  9     Odd            9     Odd
+2
source

All Articles