0

I need to create a function that returns the vector of unique values of a column of a dataframe. As input, i should mention the data frame and the column name. this is what i did :

Val_Uniques <- function(df, col) {
 return(unique(df$col))
}

Val_Uniques(mytable, city)

the result is NULL, how can i fix it please ? I want to add a trycatchblock and print awarning message "the column does not exist" if the name of the column is wrong.

Thank you in advance

Mohsen
  • 1
  • 3

2 Answers2

2

I'm sure you're looking for deparse(substitute(x)) and get() here. The former converts the specified names into strings, the latter loads your data at the first place. For the exception we simply could use an if expression.

Val_Uniques <- function(df, col) {
  df <- deparse(substitute(df))
  df <- get(df)
  col <- deparse(substitute(col))
  if(!(col %in% names(df)))
    stop("the column does not exist")
  return(unique(df[[col]]))
}

Test

> Val_Uniques(mytable, city)
[1] A D B C E
Levels: A B C D E

> Val_Uniques(mytable, foo)
Error in Val_Uniques(mytable, foo) : the column does not exist

Data

mytable <- data.frame(city=LETTERS[c(1, 4, 4, 2, 3, 2, 5, 4)],
                      var=c(1, 3, 22, 4, 5, 8, 7, 9))
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • What's an alternative to `deparse(substitute)`. I always use this but feel it's repetitive. I've seen usage of `enquo` but it often looks more work than the former. What's an "easy" alternative? – NelsonGon Jan 26 '19 at 09:45
  • 1
    Well, I would say it is a common practice to do it this way, and everyone will immediately see what your function does. – jay.sf Jan 26 '19 at 09:53
1

Try this one:

df <- data.frame(id = c("A", "B", "C", "C"),
                 val = c(1,2,3,3), stringsAsFactors = FALSE)

Val_Uniques <- function(df, col) {
  return(unique(df[, col]))
}

Val_Uniques(df, "id")

[1] "A" "B" "C"

This link helps with passing column names to functions: Pass a data.frame column name to a function

Hakki
  • 1,440
  • 12
  • 26
  • It works ! Thank you Hakki :) Do you have any idea about exception handling here ? – Mohsen Jan 26 '19 at 09:30
  • I think you should make reproducible example, but before that search tryCatch, possibly, safely and basic ifelse. – Hakki Jan 26 '19 at 09:40