Hi
I have written a function that renames the first column and then checks if the values are of lenght 2 and contain a letter. If yes, add a "0" at the beginning. I read the Programming with tidyverse but got lost so I tried the bang-bang approach. What is not working, is using the new name in the ifelse-condition. I tried with {{ }}, but that didn't work:
library(tidyverse)
add_zero <- function(data, pre) {
data %>%
rename(!!pre := colnames(data)[1]) %>%
mutate(!!pre := ifelse(
str_length(G) == 2 & str_detect(G, "[:alpha:]$"),
paste("0", G, sep = ""),
G
))
}
testdata <- tibble(sec = c("01", "2a"), year = c(2014, 2015))
(test <- add_zero(testdata, "G"))type or paste code here
I would like to have something like this and get rid of the bang bang (if possible) so that I can use another "pre" (e.g. "A" instead of "G"):
library(tidyverse)
add_zero <- function(data, pre) {
data %>%
rename(!!pre := colnames(data)[1]) %>%
mutate(!!pre := ifelse(
str_length({{ pre }}) == 2 & str_detect({{ pre }}, "[:alpha:]$"),
paste("0", {{ pre }}, sep = ""),
{{ pre }}
))
}
Cheers
Renger