In this example, I am using the iris dataset and I would like to rename Petal.Length as iris:
library(dplyr)
some_fun <- function(x){
head(x) %>%
rename(!!quo_name(x) := "Petal.Length")
}
some_fun(iris)
But this gives the following error:
Error: `expr` must quote a symbol, scalar, or call
If I use enquo instead of quo_name, I have this error:
Error: The LHS of `:=` must be a string or a symbol
I guess the problem comes from the fact that I call some_fun(iris) and not some_fun("iris"), but I have to call some_fun(iris).
How can I do that, while using some_fun(iris)?
Edit: I need this function to run through a list using purrr::map(). Updated example:
library(dplyr)
library(purrr)
list_df <- list(mtcars2 = mtcars %>% mutate(Petal.Length = 1),
iris2 = iris)
some_fun <- function(x){
df_name <- deparse(substitute(x))
head(x) %>%
rename("{df_name}" := "Petal.Length")
}
test <- map(list_df, some_fun)
list2env(test, .GlobalEnv)
mtcars2
iris2