Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a function that truncates a subset of data frame columns based on a list of field length values in R?

I have a data frame in which some of the fields need to be truncated to different lengths. Here is a sample data:

library(dplyr)

id <- c(1111, 2222, 3333, 4444, 5555)
first_name <- c("Jonathan", "Sally", "Courtney", "Stephen", "Matthew")
last_name <- c("Johnson", "Montgomery", "Cunningham", "Stephenson", "Matthews")
Height <- c(200, 160, 170, 180, 190)
 
df <- data.frame(id, first_name, last_name, Height, stringsAsFactors = FALSE)

I want to truncate first_name and last_name columns to the corresponding lengths of 3 and 5. I created a simple function that accepts a data frame, field name and field length.

truncate_fields <- function(df, field, n) {
  df_tr <-
    mutate(df, {{field}} := str_trunc({{field}}, n, ellipsis = ""))
  return(df_tr)
}

The function works great. I now want to apply it to a subset of columns using a list of lengths.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fields <- c("first_name", "last_name")
lengths <- c(3, 5)

for(i in 1:length(fields)) {
  df <-
    truncate_fields(df, noquote(fields)[i], lengths[i])
}

However I get the following error:

Error in `splice()`:
! The LHS of `:=` must be a string or a symbol

I also tried lapply and mapply without much success. Any help is greatly appreciated. Thank you.

>Solution :

The noquote function only affects how string values are printed the the console. noquote("variable") is very different from just variable. If you want to turn a string into a symbol, you can use rlang::sym and inject that into the calling expression with !!. So the following will work

for(i in 1:length(fields)) {
  df <-
    truncate_fields(df, !!rlang::sym((fields)[i]), lengths[i])
}

and that will be logically equivalent to

df <- truncate_fields(df, first_name, 3)
df <- truncate_fields(df, last_name, 5)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading