I have this user-defined function that works stand-alone but not in a dplyr
pipe.
What am I doing wrong?
# Function to add the object name as a new dataframe column, and
# move it to first position
library(tidyverse, quietly=TRUE)
name_as_column <- function(.data) {
object_name <- as.character(substitute(.data))
.data$obj_name <- object_name
y <- "obj_name"
.data <- .data[,c(y, setdiff(names(.data), y))]
return(.data)
}
# Works here
head(name_as_column(mtcars))
#> obj_name mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 mtcars 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag mtcars 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 mtcars 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive mtcars 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout mtcars 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
#> Valiant mtcars 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
head(name_as_column(iris))
#> obj_name Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 iris 5.1 3.5 1.4 0.2 setosa
#> 2 iris 4.9 3.0 1.4 0.2 setosa
#> 3 iris 4.7 3.2 1.3 0.2 setosa
#> 4 iris 4.6 3.1 1.5 0.2 setosa
#> 5 iris 5.0 3.6 1.4 0.2 setosa
#> 6 iris 5.4 3.9 1.7 0.4 setosa
# Doesn't work in dplyr pipe
mtcars %>%
name_as_column(.) %>%
head()
#> obj_name mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 . 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag . 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 . 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive . 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout . 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
#> Valiant . 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Created on 2021-02-12 by the reprex package (v1.0.0)