ifelse较长的对象长度不是较短对象长度的倍数

时间:2015-02-20 21:51:33

标签: r if-statement dplyr

我正在做一个简单的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")

1 个答案:

答案 0 :(得分: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