簡體   English   中英

r是否基於多個條件

[英]r if else based on multiple conditions

我有一個數據集data1如下

          Group     Code
          Blue      1333
          Blue      4444
          Blue      9876
          Blue      8785
          Red       3145
          Red       8756
          Red       9745
          Red       8754

第二數據集data2如下

          Id       Description
          1333     Sea Weed
          4444     Honey Roasted Peanut
          8754     Green Tea
          8756     Potato Chips
          3145     Strawberry Grahams
          8787     Arizona Ice Tea

我正在嘗試在第二個數據集data2中創建第三列,該列存儲

           1  - If the code is from blue Group in Data1 and matches with Id in Data2, Data1$Group = Blue && Data1$Code == Data2$Id

           2  - If the code is from Red Group in Data1 and matches with Id in Data2, Data1$Group = Red && Data1$Code == Data2$Id

           0  - If the Id in Data2 does not match the Code in Data1 , regardless of whether it is Blue or Red group.

最終數據集應如下所示

          Id       Description             Result
          1333     Sea Weed                1  
          4444     Honey Roasted Peanut    1
          8754     Green Tea               2
          8756     Potato Chips            2 
          3145     Strawberry Grahams      2 
          8787     Arizona Ice Tea         0

需要一些協助

最簡單的R答案是使用merge

> merge(data1, data2, by.x='Code', by.y='Id', all.y=T)

  Code Group          Description
1 1333  Blue             Sea Weed
2 3145   Red   Strawberry Grahams
3 4444  Blue Honey Roasted Peanut
4 8754   Red            Green Tea
5 8756   Red         Potato Chips
6 8787  <NA>      Arizona Ice Tea

如果您dplyr使用dplyr ,那么重命名該列是最簡單的方法是重命名該列,使其與合並的表匹配

data2 %>% rename(Code=Id) %>% left_join(data1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM