Reputation: 1
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
Upvotes: 0
Views: 50
Reputation: 72593
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))
Upvotes: 2
Reputation: 1472
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
Upvotes: 1