【问题标题】:ifelse longer object length is not a multiple of shorter object length [duplicate]ifelse较长的对象长度不是较短对象长度的倍数[重复]
【发布时间】:2015-02-20 21:51:32
【问题描述】:

我正在做一个简单的 ifelse 语句,将 Dataset1 中的 code1 与 code2 Dataset2 进行比较,我看到了

Warning message:
In Data1$code == Data2$code :
longer object length is not a multiple of shorter object length

数据1

  Id  Code    Date
  1   100     01/01/83
  2   101.28  04/17/76
  3   250.23  01/02/99
  4   312.45  02/26/82
  5   NA      12/12/90
  6   NA      11/06/89

数据2

  Id  Code      Description
  1   100       2 bedroom 1 bath
  2   287.45    Studio
  3   250.23    3 bedroom 2 bath
  4   250.23    3 bedroom 2 bath
  5   187.23    Condo 1 bed 1bath
  6   312.45    town house

输出

  Id  Code      Description         Result
  1   100       2 bedroom 1 bath    Yes
  2   287.45    Studio              No
  3   250.23    3 bedroom 2 bath    Yes
  4   250.23    3 bedroom 2 bath    Yes
  5   187.23    Condo 1 bed 1bath   No
  6   312.45    town house          Yes

这就是我所做的

   Data2$Result <- ifelse(Data1$code == Data2$code), "Yes", "No")

【问题讨论】:

    标签: r if-statement dplyr


    【解决方案1】:
    # convert your structures to data.table
    library(data.table)
    setDT(Data1)
    setDT(Data2)
    
    # set the key for the merge
    setkey(Data1, Code)
    setkey(Data2, Code)
    
    # the actual work - create a Result column and prefill with 'No'
    # then fill the ones that match with 'Yes'
    Data2[, Result := 'No'][Data1, Result := 'Yes']
    Data2
    #   Id   Code       Description Result
    #1:  1 100.00  2 bedroom 1 bath    Yes
    #2:  5 187.23 Condo 1 bed 1bath     No
    #3:  3 250.23  3 bedroom 2 bath    Yes
    #4:  4 250.23  3 bedroom 2 bath    Yes
    #5:  2 287.45            Studio     No
    #6:  6 312.45        town house    Yes
    

    【讨论】:

    • 警告消失了,但是当代码中有 NA 时,这个逻辑会起作用
    • 我不知道你的意思-举个例子
    • 请给我1小时,我会回复的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多