Haakonkas
Haakonkas

Reputation: 1041

Adding to columns with paste in mutate_at

I have the following test data:

structure(list(testcode = structure(1:3, .Label = c("1", "20", 
"300"), class = "factor"), testname = structure(c(2L, 3L, 1L), .Label = c("Bed", 
"Book", "Car"), class = "factor")), .Names = c("testcode", "testname"
), row.names = c(NA, -3L), class = "data.frame")

I have a function that identifies a specific column name, then adds a leading zero to the variables in that column as a character. (All the columns are character). Since the column variables in the "code" column is of variable length, I thought it was easiest to use paste0 as paste0("0",column_name).

The function is as follows:

library(dplyr)

fix_codes <- function(df) {
  code_column <- grep("code$", colnames(df), value = TRUE)

  df <- df %>%
    mutate_at(.vars = code_column, .funs = funs(paste0("0",code_column)))
  return(df)
}

However, paste0 does not seem to understand that I want to paste together the column that is specified by code_column, and not "code_column" itself, as it does now. How do I make paste0 recognize it correctly?

What I want to end up with:

testcode   testname
01         Book
020        Car
0300       Bed

Upvotes: 2

Views: 803

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

We can use . instead to apply paste on actual values of selected columns

fix_codes <- function(df) {
   code_column <- grep("code$", colnames(df), value = TRUE)
   df <- df %>%
       mutate_at(.vars = code_column, .funs = funs(paste0("0",.)))
   return(df)
}

df

#  testcode testname
#1        1     Book
#2       20      Car
#3      300      Bed

fix_codes(df)
#  testcode testname
#1       01     Book
#2      020      Car
#3     0300      Bed

Also the equivalent base R approach using lapply would be where we select the columns directly

df[grep("code$", colnames(df))][] <- 
         lapply(df[grep("code$", colnames(df))], function(x) paste0("0", x))

Upvotes: 2

Related Questions