0

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.

mbuechmann
  • 5,413
  • 5
  • 27
  • 40
Nabil
  • 19
  • 1
  • 1
    It should be `if (colname %in% colnames(dataframe)) { ...` - you are missing the brackets after `if`. Also check the spelling of your second argument: `datframe`. It should be `dataframe` I guess. – markus Sep 29 '18 at 20:52
  • Thanks , i've done this , but i keep getting this error : Error: unexpected 'else' in "else" > } Error: unexpected '}' in "}" – Nabil Sep 29 '18 at 21:13
  • My new code looks like this : – Nabil Sep 29 '18 at 21:14
  • val_uniques <- function (colname,dataframe) if (colname %in% colnames(dataframe)){ print( unique(dataframe[,colname] , incomparables = FALSE)) } else {print("cette colonne n'existe pas") } – Nabil Sep 29 '18 at 21:14
  • You have both `datframe` and `dataframe`. Correct that and it works. Oh, use open `{` and close `}` to start and end the function, it's more readable. – Rui Barradas Sep 29 '18 at 21:16
  • 1
    You are missing the `{` bracktes after `function (colname,dataframe)`. Try `val_uniques <- function (colname,dataframe) {if (colname %in% colnames(dataframe)){ print( unique(dataframe[,colname] , incomparables = FALSE)) } else {print("cette colonne n'existe pas") }}` – markus Sep 29 '18 at 21:18
  • Thanks very much , it worked now. – Nabil Sep 29 '18 at 21:29

1 Answers1

0

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
Artem
  • 3,304
  • 3
  • 18
  • 41