条件匹配

问题描述 投票:0回答:1

我有两个变量。我想看看它们是否在另一个变量中。基于此匹配,我想从与该匹配的行关联的同一数据集中返回一个值到一个新变量中。条件是,如果不匹配,我要使用变量之一的值。

              df
                     Name              Name1             Name2 
                     Natalie             Shawn              Edmund
                      Desmond             Desmond            James
                       Kylie               Kylie             Brent


               Desired output

                df
                         Name          Name1             Name2            Fullname
                         Natalie     Shawn              Edmund            Natalie
                         Desmond     Desmond            Desmond James     Desmond James
                          Kylie       Kylie            Kylie Brent        Kylie Brent

               I've tried:

                    df$Fullname <- (df$Name2[match(df$Name, df$Name1)])

 This gives me the full name  variable (i.e. Desmond James and Kylie Brent). Where I'm struggling is the conditional part and return a value when the variables don't match.  I've considered doing an ifelse nested coding but I'd like to stay from that as my dataset is rather large.

感谢您的帮助!

r matching
1个回答
0
投票

我们可以使用ifelse创建条件(假设列为character类)

df$Fullname <- with(df, ifelse(Name == Name1, paste(Name, Name2), Name))
© www.soinside.com 2019 - 2024. All rights reserved.