Why do I get “number of items to replace is not a multiple of replacement length”

前端 未结 2 633
旧巷少年郎
旧巷少年郎 2021-02-05 02:25

I have a dataframe combi including two variables DT and OD.

I have a few missing values NA in both DT and OD but not necessary the same record.

I then try to rep

相关标签:
2条回答
  • 2021-02-05 02:53

    The warning is produced because you are trying to assign all combi$OD to the places where combi$DT is NA. For example if you have 100 rows of 2 variables with 5 NAs, then you are telling it to replace those 5 NAs of variable1 with the 100 values of variable2. Hence the warning. Try this instead,

    combi$DT[is.na(combi$DT) & !is.na(combi$OD)] <- combi$OD[is.na(combi$DT) & !is.na(combi$OD)]
    
    0 讨论(0)
  • 2021-02-05 03:12

    Because the number of items to replace is not a multiple of replacement length. The number of items to replace is the number of rows where is.na(combi$DT) & !is.na(combi$OD) which is less than the number of rows in combi (and thus the length of the replacement).

    You should use ifelse:

    combi$DT <- ifelse(is.na(combi$DT) & !is.na(combi$OD), combi$OD, combi$DT)
    

    N.B. the & !is.na(combi$OD) is redundant: if both are NA, the replacement will be NA. So you can just use

    combi$DT <- ifelse(is.na(combi$DT), combi$OD, combi$DT)
    
    0 讨论(0)
提交回复
热议问题