datax
datax

Reputation: 21

"Or" operator is not working as expected in R

I am trying to created a function as below:

remove_loan_apl <- function(x) {
  if((x==0) || (is.NA(x))) {x <- 100000} 
   return(x)
}
remove_loan_apl <- function(x) {
  if((x==0) || (x is NA)) {x <- 100000} 
   return(x)
}

But its not working. What is the correct method to apply or for the missing value? I expect the function to replace value of x to 100000, where it is 0 or missing(NA)

Upvotes: 1

Views: 1582

Answers (1)

Dhawal Kapil
Dhawal Kapil

Reputation: 2757

May be I can guess what you are doing.

This function as suggested by Pierre Lafortune

remove_loan_apl <- function(x) {
    if((x==0) || (is.na(x))) {x <- 100000} 
    return(x)
}

should work.

I think what you are trying to do is pass a complete vector of mixed values non-na,0 and NA to x. If you pass a complete vector this function will not work and will return your vector as it is.

For eg.

x=c(1,NA,2,3,NA,4,0,5)

If you will do

remove_loan_apl(x)

It will return x vector as it is.

Output :

1 NA  2  3 NA  4  0  5

You will have to lapply or sapply to apply your function to each and every value of your vector.

sapply(x,remove_loan_apl)

This will give the output as desired :

1 100000      2      3 100000      4 100000      5

Upvotes: 1

Related Questions