Skip to content

Instantly share code, notes, and snippets.

@johnmackintosh
Created August 30, 2022 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmackintosh/7826f9bc4d6854624a353e336da2eb3d to your computer and use it in GitHub Desktop.
Save johnmackintosh/7826f9bc4d6854624a353e336da2eb3d to your computer and use it in GitHub Desktop.
how to use lapply and .SD to update columns within rdatatable
# columns to update:
char_cols <- c("areaname", "parent_area")
# 1. convert to character, then
# 2. replace '&' with 'and'
DT[,(char_cols) := lapply(.SD, as.character), .SDcols = char_cols]
DT[,(char_cols) := lapply(.SD, gsub, pattern = ' & ', replacement = ' and '), .SDcols = char_cols]
# Or do both at once by chaining:
DT[,(char_cols) := lapply(.SD, as.character), .SDcols = char_cols
][,(char_cols) := lapply(.SD, gsub, pattern = ' & ', replacement = ' and '), .SDcols = char_cols]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment