I am trying to create a function that will mutate a column if it exists. If the column does exist, I return a data frame with two columns. I'd like help unpacking this data frame column, into its component columns:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
my_transformation = function(df){
df %>%
mutate(across(any_of('cyl'), function(x) tibble(a = x + 3, b = x + 1)))
}
df_1 = as_tibble(mtcars)
df_2 = df_1 %>% select(-cyl)
my_transformation(df_1)
#> # A tibble: 32 x 11
#> mpg cyl$a $b disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 21 9 7 160 110 3.9 2.62 16.5 0 1 4 4
#> 2 21 9 7 160 110 3.9 2.88 17.0 0 1 4 4
#> 3 22.8 7 5 108 93 3.85 2.32 18.6 1 1 4 1
#> 4 21.4 9 7 258 110 3.08 3.22 19.4 1 0 3 1
#> 5 18.7 11 9 360 175 3.15 3.44 17.0 0 0 3 2
#> 6 18.1 9 7 225 105 2.76 3.46 20.2 1 0 3 1
#> 7 14.3 11 9 360 245 3.21 3.57 15.8 0 0 3 4
#> 8 24.4 7 5 147. 62 3.69 3.19 20 1 0 4 2
#> 9 22.8 7 5 141. 95 3.92 3.15 22.9 1 0 4 2
#> 10 19.2 9 7 168. 123 3.92 3.44 18.3 1 0 4 4
#> # … with 22 more rows
my_transformation(df_2)
#> # A tibble: 32 x 10
#> mpg disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 21 160 110 3.9 2.62 16.5 0 1 4 4
#> 2 21 160 110 3.9 2.88 17.0 0 1 4 4
#> 3 22.8 108 93 3.85 2.32 18.6 1 1 4 1
#> 4 21.4 258 110 3.08 3.22 19.4 1 0 3 1
#> 5 18.7 360 175 3.15 3.44 17.0 0 0 3 2
#> 6 18.1 225 105 2.76 3.46 20.2 1 0 3 1
#> 7 14.3 360 245 3.21 3.57 15.8 0 0 3 4
#> 8 24.4 147. 62 3.69 3.19 20 1 0 4 2
#> 9 22.8 141. 95 3.92 3.15 22.9 1 0 4 2
#> 10 19.2 168. 123 3.92 3.44 18.3 1 0 4 4
#> # … with 22 more rows
Created on 2020-08-22 by the reprex package (v0.3.0)
As you can see, when calling my_transformation(df_1)
, there are two subcolumns: cyl$a
and cyl$b
. How do I get these to be regular columns?
I have tried unnest(cyl)
but had no success.