dplyr mutate across columns using column name in function

Hi,

I'm sorry for the confusing title, but I want to do the following:
Given a data frame with unknown columns, I want to mutate certain ones if present, and use the column name in the mutation.

Example:
I have a data frame with unknown column names (in this case x and y). I want to mutate the columns y and z if they exist where the new value looks like <columns name> = <value>. So for y that would be y = a, y = b, ...

I've gotten as far as finding the correct filtering of column and merging the values, but I can't think of a solution on how to get the column name passed to the function as names (.) results in an error

library(dplyr)
 
test = data.frame(x = 1:5, y = letters[1:5])

test %>% mutate(across(matches("^(y|z)$"), ~sprintf("%s = %s", ., .)))
#>   x     y
#> 1 1 a = a
#> 2 2 b = b
#> 3 3 c = c
#> 4 4 d = d
#> 5 5 e = e

Created on 2020-08-10 by the reprex package (v0.3.0)

So I want the y column to look like y = <value> instead of now <value> = <value>

PJ

1 Like

cur_column() is what you're looking for

5 Likes

Hi,

Thanks for the solution! I had no idea these cur_ functions existed and it did the job!

library(dplyr)

test = data.frame(x = 1:5, y = letters[1:5])

test %>% mutate(across(matches("^(y|z)$"), ~sprintf("%s = %s", cur_column(), .)))
#>   x     y
#> 1 1 y = a
#> 2 2 y = b
#> 3 3 y = c
#> 4 4 y = d
#> 5 5 y = e

Created on 2020-08-10 by the reprex package (v0.3.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.