use assignment or gsub to replace values in R

  • If the value to be replaced is the entire cell value (like replacing “-” with 0), it’s easier to use simple assignment. For the rest, we can use gsub together with lapply

    • We need to use gsub to allow us to use regex feature to find a specific string to replace, while lapply() function is more efficient when you need to do so on multiple columns
# simple assignment if we can "regex" the entire cell value
df_sum[df_sum=="-"] <- 0

# gsub with lapply is better when you have to knitpick certain string
df_sum = lapply(df_sum, FUN=function(x) gsub(",", "", x)) %>% as.data.frame()

Metadata

  • topic:: 00 Coding00 Coding
    #MOC / for programming language, coding guide and libraries focusing on data analytics and html/css
    • related:: 01 R programming01 R programming
      #MOC / for notes sub to 00 Coding with focus on how I use Jekyll
  • updated:: 2022-08-28 Private or Broken Links
    The page you're looking for is either not available or private!
  • reviewed:: 2022-08-28 Private or Broken Links
    The page you're looking for is either not available or private!
  • #Reference