Home > Software design >  Print line for NA value in dataframe in R
Print line for NA value in dataframe in R

Time:10-28

I want function to check if value of count = NA then it will print out the line say that "Not valid" or else it will say "Succees"

order = data.frame(item = c("A","B","C"), count = c(1,2,NA))

check <- function(order){
  if (order$count[is.na(order$count),] ){
    print(paste(order$item,"not value"))
  }
  else {
    print("success")
  }
}

But it generates the errors

CodePudding user response:

I think you could shorten the whole function like so:

# define function:

check <- function(x) { 
  ifelse(is.na(x), "not value", "success")
}

# input function:

check(order$count)
[1] "success"   "success"   "not value"

CodePudding user response:

You may try this way

check <- function(order){
  if (any(is.na(order$count)) ){
    print(paste(order$item[is.na(order$count)],"not value"))
  }
  else {
    print("success")
  }
}
check(order)

[1] "C not value"

Reason of error Error in order$count[is.na(order$count), ] : incorrect number of dimensions is that order$count is vector but you call [is.na(order$count), ].

Also, order$count[is.na(order$count)] is NA, it's not appropriate to input as a condition for if statement.

If you want to check items row-wise, you may try

check <- function(order){
  for (i in 1:nrow(order)){
    if (is.na(order$count[i])) {
      print(paste(order$item[i], "not value"))
    } else {
      print(paste(order$item[i], "success"))
    }
  }
}
check(order)  

[1] "A success"
[1] "B success"
[1] "C not value"

CodePudding user response:

Here is an alternative way:

library(car)
recode(is.na(order$count), "FALSE='success'; TRUE='not valid'")
[1] "success"   "success"   "not valid"
  • Related