I want to add a new variable in an dplyr workflow and define the variable name based on a condition. There is a lot of discussion on conditional mutating with ifelse()
out there on how to define values of a given variable, but not on how to conditionally define the name.
Something like:
Test <- 'A'
Test_results <- c(1.1, 33, 343, 2.22, 2.4)
##
iris<- iris%>%
dplyr::mutate(
ifelse(Test=='A',
Test_A=Test_results,
ifelse(Test=='B',
Test_B=Test_results,
no_Test='no_results')) )
Desired output (given that Test <- 'A'
) is:
> iris
Sepal.Length Sepal.Width Petal.Length Petal.Width Species Test_A
1 5.1 3.5 1.4 0.2 setosa 1.1
2 4.9 3.0 1.4 0.2 setosa 33
3 4.7 3.2 1.3 0.2 setosa 343
4 4.6 3.1 1.5 0.2 setosa 2.22
5 5.0 3.6 1.4 0.2 setosa 2.4
...
If Test <- 'B'
the result should be:
> iris
Sepal.Length Sepal.Width Petal.Length Petal.Width Species Test_B
1 5.1 3.5 1.4 0.2 setosa 1.1
2 4.9 3.0 1.4 0.2 setosa 33
3 4.7 3.2 1.3 0.2 setosa 343
4 4.6 3.1 1.5 0.2 setosa 2.22
5 5.0 3.6 1.4 0.2 setosa 2.4
...
The variable "Test" is defined somewhere in the users cockpit and does effects on multiple nested scripts (so no hard coding pls).
dplyr::rename_at
should work. Create a column with the tests and rename it with a function that depends on Test
.
Test <- 'A'
Test_results <- c(1.1, 33, 343, 2.22, 2.4)
iris %>%
head(n = 5) %>%
mutate(Test_results = Test_results) %>%
rename_at('Test_results', \(x) case_when(Test %in% c('A', 'B') ~ paste0('Test_', Test),
TRUE ~ 'no_results'))