Home > front end >  If else based on unique column values
If else based on unique column values

Time:03-25

I want to print different messages if the values in a column are unique or not unique

df <- data.frame (test  = c(1,1,1,2,2),
                  number = c(3,7,5,1,6)
)

if(unique(df$test)){
  print("unique")
  
  } else {
    print("not unique")
    }

should print "not unique" since test does not have unique numbers. I get this warning message: [1] "unique" Warning message: In if (unique(df$test)) { : the condition has length > 1 and only the first element will be used

CodePudding user response:

unique(df$test) returns the vector of unique values and not a logical vector. We need a logical vector of length 1 in if and that can be done by wrapping with length and check if the length is the same as the number of elements (length(df$test) or number of row in this case as it is a data.frame nrow(df))

 if(length(unique(df$test)) == nrow(df)){
  print("unique")
  } else {
    print("not unique")
    }
  •  Tags:  
  • r
  • Related