jeudi 17 décembre 2015

Replace NA by zero through ifelse

I have a dataframe with the following information (this is a small part):

Treenr Liananr DBH LianaLoad
4      NA      55  1
6      NA      60  1
10     3       50  1

My problem now is, that if Liananr is NA, I want to replace LianaLoad by 0. If it is not NA, I want to keep the value that's in column LianaLoad. So this would be the result:

Treenr Liananr DBH LianaLoad
4      NA      55  0
6      NA      60  0
10     3       50  1

I tried the following:

dfAll2$LianaLoad <- ifelse(is.na(dfAll2$Liananr), NULL, dfAll2$Lianaload)
dfAll2$LianaLoad <- ifelse(is.na(dfAll2$Liananr), 0, dfAll2$Lianaload)
dfAll2$LianaLoad <- ifelse(is.na(dfAll2$Liananr), '0', dfAll2$Lianaload)
dfAll2$LianaLoad <- ifelse(dfAll2$Liananr %in% NA, NULL, dfAll2$Lianaload)

None of them would work, I received the following error:

Error in ifelse(is.na(dfAll2$Liananr), 0, dfAll2$Lianaload) : 
  replacement has length zero
In addition: Warning message:
In rep(no, length.out = length(ans)) :
  'x' is NULL so the result will be NULL

Aucun commentaire:

Enregistrer un commentaire