R:比较不同级别的字符串变量



我可以知道如何比较R中具有不同级别的两个字符串变量吗?

我想检查变量 Q1 是否与 Q2 匹配,以便我以后可以对我的数据进行一些验证

Key  Q1      Q2               
 1   Apple   Pineapple       
 2   Banana  Banana              
 3   Apple   Papaya              
 4   Orange  ""                    
 5   Papaya  ""                 
 6   Apple   Apple          

并有如下结果

Key  Q1      Q2          Result           
 1   Apple   Pineapple   No   
 2   Banana  Banana      Yes           
 3   Apple   Papaya      No             
 4   Orange  ""          No                      
 5   Papaya  ""          No              
 6   Apple   Apple       Yes        

我收到一条错误消息,指出

"level sets of factors are different"

$ Q1    : Factor w/ 4 levels "Apple","Banana",..: 1 2... 
$ Q2    : Factor w/ 5 levels "","Pineapple","Banana"...

谁能帮忙?

多谢。

试试这个:

Q1 = c("Apple", "Banana", "Apple", "Orange", "Papaya", "Apple")
Q2 = c("Pineapple", "Banana", "Papaya", "", "", "Apple")
df = as.data.frame(cbind(Q1, Q2))
df$Q1 = as.character(df$Q1)
df$Q2 = as.character(df$Q2)
df$Results = ifelse(df$Q1 == df$Q2, "Yes", "No")
df
> df
      Q1        Q2 Results
1  Apple Pineapple      No
2 Banana    Banana     Yes
3  Apple    Papaya      No
4 Orange                No
5 Papaya                No
6  Apple     Apple     Yes

相关内容

  • 没有找到相关文章

最新更新