We can use [[, pass the column name as string and return the dataset in the function
test <- function(x,q,y,z) {
x[[q]] <- gsub(y, z, x[[q]])
x
}
test(df, "X1.10", "1", "2")
-output
# rep.1..10. X1.10 rep.5..10.
#1 1 2 5
#2 1 2 5
#3 1 3 5
#4 1 4 5
#5 1 5 5
#6 1 6 5
#7 1 7 5
#8 1 8 5
#9 1 9 5
#10 1 20 5
If we need to change only a fixed match and no substring, we don't need a gsub, it can be just == i.e. create a logical expression with == and use that to assign
test <- function(x,q,y,z) {
i1 <- x[[q]] == y
x[[q]][i1] <- z
x
}
test(df, "X1.10", "1", "2")
# rep.1..10. X1.10 rep.5..10.
#1 1 2 5
#2 1 2 5
#3 1 3 5
#4 1 4 5
#5 1 5 5
#6 1 6 5
#7 1 7 5
#8 1 8 5
#9 1 9 5
#10 1 10 5
With regex, one option is add the start (^) and end ($) by pasteing. Also, if this occurs only once, then we need to use only sub and not gsub (global substitution)
test <- function(x,q,y,z) {
y <- paste0("^", y, "$")
x[[q]] <- sub(y, z, x[[q]])
x
}
test(df, "X1.10", "1", "2")
In case, we want to pass unquoted column names, use deparse/substitute
test <- function(x,q,y,z) {
q <- deparse(substitute(q))
x[[q]] <- gsub(y, z, x[[q]])
x
}
test(df, X1.10, "1", "2")