I'm building a shiny app where certain columns in my data frame will need to be mutated using a simple linear transformation, but the total number of these columns can change, as well as the location of these columns in the data frame. However, the column names have a specific naming convention that I believe makes it possible to develop a dynamic solution. I'm simply stuck on how to accomplish this aim.
Here are the core features of my data:
- In the example code below you will see several columns labeled a#. These are the columns that I will use to mutate additional columns into my data frame.
- In my Shiny app, these a# columns are created dynamically based on the input file selected by the user and the model applied to the data on the back-end.
- These columns are always generated with the same name (i.e., a#), where the 'a' is constant and the # varies sequentially based on factors in my model that are not relevant to the current question.
Goal:
- What I would like to be able to do is dynamically apply the linear transformation in the code below to every potential value that could appear in the df with the label a#. I have a hunch this involves a
dplyr
solution that watches for strings, but I'm more stuck on how to get the solution to adapt to any a# variable. - Preferably, I'd like to use a tidy solution.
Thanks.
Code:
library(tibble)
library(dplyr)
dat <- tibble (
a1 = rnorm (100, 0, 1),
b = rnorm (100, 0, 1),
a2 = rnorm (100, 0, 1),
c = rnorm (100, 0, 1)
)
# single vector working example of the transformation applied to one column (need dynamic version).
dat <- dat %>%
mutate(
a1_T = 10*a1 + 50
)