0

Super noob question but I cant find the answer. Dont understand why the variable reference isnt working. Would appreciate if anyone could forward me to a post where I could learn about this. Thanks

factor_check <- function(x,y) {
   unique(x$y)
}

factor_check(data , variable)
sj95126
  • 6,520
  • 2
  • 15
  • 34

2 Answers2

0

The $ operator is not as flexible as the [ operator for subsetting. There you can pass a string as a column name to do what you're looking for. From ?Extract:

Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]].

So, for your example that would look something like:

f <- function(dat, col) {dat[[col]]}

f(mtcars, "cyl")
#>  [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

Created on 2022-07-22 by the reprex package (v2.0.1)

Dan Adams
  • 4,971
  • 9
  • 28
0

You could use the embrace operator with dply::pull(), if you need to pass cyl without quotation marks. Links below explain the rlang operator.

factor_check <- function(x,y) {
   unique( dplyr::pull(x, {{y}} ))
}
factor_check(mtcars, cyl)

https://rlang.r-lib.org/reference/embrace-operator.html

What is the "embracing operator" `{{ }}`?

parmsam
  • 19
  • 3