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.
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.
Update:
Using an older version of dplyr (0.7.4.)