Change cell name in R using a function

Viewed 55

Consider the following data frame:

df <- data.frame(rep(1,10),1:10,rep(5,10))

I want to replace all the cells with the value 1 in column two with the value 2. I want to create a function that do that. I create the following function:

test <- function(x,q,y,z) {
  x$q <- gsub(y, z, x$q)
}

But when I apply the code:

df$X1.10 <- test(df,X1.10,"1","2")

I get an error. Why do I get an error? It is working if I don't include the "z" parameter in the function.

1 Answers

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")
Related