How to extract unique values from a data frame column?

318 Views Asked by At

I've been trying to create a function that extracts the unique values of a given column in a given data frame, by writing this code:

val_uniques <- function(colname, datframe)
  if colname %in% colnames(dataframe) {
    print(unique(dataframe[, colname], incomparables = FALSE))
  } else {
    print("cette colonne n'existe pas")
  }

but unfortunately, I keep getting this error :

print( unique(dataframe[,colname] , incomparables = FALSE))} else { print("cette colonne n'existe pas")} Error: unexpected '}' in "print( unique(dataframe[,colname] , incomparables = FALSE))}"

I know it's a dumb question because it has something to do with } in if or else, but I've tried everything and it didn't work.

P.S. It's my first programming stuff in R.

1

There are 1 best solutions below

0
On BEST ANSWER

There are some typos in object names datframe and dataframe as well as curly brackets are misplaced:

val_uniques <- function(colname, dataframe) {
  if (colname %in% colnames(dataframe)) {
    print(unique(dataframe[, colname] , incomparables = FALSE))
  } else {
    print("cette colonne n'existe pas")
  }
}

df <- data.frame(a = c(1, 1, 3, 4), b = 1:4)

val_uniques("a", df)
# [1] 1 3 4