循环以基于R中的其他情况创建一个新变量(非常基础) [英] loop to create a new variable based on other cases in R (very basic)
问题描述
我有一个带有三个变量的数据框:ID
,group
和nominated_ID
.
我想知道nominated_ID
所属的group
.
I have a dataframe with three variables: ID
, group
, and nominated_ID
.
I want to know the group
that nominated_ID
belongs in.
我想对于每种情况,我们采用nominated_ID
,找到等于ID
的情况,然后将原始情况下的nominated_Group
变量设置为等于匹配的情况. (如果没有匹配项,请将其设置为NA)
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.
推荐答案
通过直接将结果分配到data.frame中的一列,您可以在不使用cbind
的情况下一步实现此目的:
You can achieve this in one step without the use of cbind
by directly allocating results to a column in your 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$
.
I used with
as a convenient way of referring to the columns of df without having to repeatedly write df$
.
这篇关于循环以基于R中的其他情况创建一个新变量(非常基础)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!