0

I want define a function

factor <- function(var1)
  {
     df['var1'] <- as.factor(df['var1'])
  }

to transform type of variable

and use like that factor(var1) without quote!

Hack-R
  • 22,422
  • 14
  • 75
  • 131
n_t
  • 1
  • 4
  • You probably don't really want to hard-code a data set name in your function. You just pass in a variable name, which can be a column in a `data.frame`. However, this function is identical to using `as.factor()` directly, so I'm not sure what you're trying to accomplish? – Hack-R Jul 02 '18 at 16:57
  • 2
    http://adv-r.had.co.nz/Computing-on-the-language.html – Roland Jul 02 '18 at 17:17
  • 1
    Pose a clear question and choose a title that attracts the right people – Dirk Horsten Jul 02 '18 at 20:45

2 Answers2

1

Using tidyeval approach, you can use rlang::sym to convert string to symbol then unquote it inside mutate with !!. See also this answer.

library(rlang)
library(tidyverse)

# create a test data frame
iris1 <- head(iris) %>% 
  as.tibble() %>% 
  mutate(Species = as.character(Species))
iris1

#> # A tibble: 6 x 5
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>          <dbl>       <dbl>        <dbl>       <dbl> <chr>  
#> 1          5.1         3.5          1.4         0.2 setosa 
#> 2          4.9         3            1.4         0.2 setosa 
#> 3          4.7         3.2          1.3         0.2 setosa 
#> 4          4.6         3.1          1.5         0.2 setosa 
#> 5          5           3.6          1.4         0.2 setosa 
#> 6          5.4         3.9          1.7         0.4 setosa

str(iris1)

#> Classes 'tbl_df', 'tbl' and 'data.frame':    6 obs. of  5 variables:
#>  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4
#>  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9
#>  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7
#>  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4
#>  $ Species     : chr  "setosa" "setosa" "setosa" "setosa" ...

# build function
myfactor <- function(df, var1)
{
  var1 <- sym(var1)
  df <- df %>% mutate(!! var1 := as.factor(!! var1))
  return(df)
}

myfactor(iris1, 'Species')

#> # A tibble: 6 x 5
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>  
#> 1          5.1         3.5          1.4         0.2 setosa 
#> 2          4.9         3            1.4         0.2 setosa 
#> 3          4.7         3.2          1.3         0.2 setosa 
#> 4          4.6         3.1          1.5         0.2 setosa 
#> 5          5           3.6          1.4         0.2 setosa 
#> 6          5.4         3.9          1.7         0.4 setosa

Created on 2018-07-02 by the reprex package (v0.2.0.9000).

Tung
  • 26,371
  • 7
  • 91
  • 115
0

you need to use substitute to capture the variable name then make is a name/character by deparse

facr <- function(var1)
{
  v=deparse(substitute(var1))
  df[v] <- as.factor(df[[v]])
  df
}
Onyambu
  • 67,392
  • 3
  • 24
  • 53