Home > database >  Simplifying column edit using stringr and pipes instead of gsub
Simplifying column edit using stringr and pipes instead of gsub

Time:01-12

I am trying to remove the $ sign and , from a column and have so far been doing so by using gsub but am wondering if there is a way to do it using stringr inside pipes.

Example Code:

DataFrame <- structure(list(Date = structure(c(18485, 18459, 18471, 18459, 
18459, 18459, 18499, 18513, 18513, 18513), class = "Date"), Payment = c("$10,000.00", 
"$2,000.00", "$500.00", "$500.00", "$5,000.00", "$4,000.00", 
"$5,000.00", "$500.00", "$20,000.00", "$3,290.00")), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

Current approach using gsub:

DataFrame$Payment <-gsub("\\$","",DataFrame$Payment)
DataFrame$Payment <-gsub("\\,","",DataFrame$Payment)
DataFrame$Payment <- as.numeric(DataFrame$Payment)

Thanks for the pointers!

CodePudding user response:

Well actually gsub with a character class is already pretty terse:

DataFrame$Payment <- as.numeric(gsub("[$,]", "", DataFrame$Payment))

CodePudding user response:

Pretty much anything can moved inside a mutate:

DataFrame %>% 
    mutate(Payment = as.numeric(gsub('\\$|\\,', '', Payment)))

If you want to use stringr, then try this:

DataFrame %>% 
    mutate(Payment = as.numeric(stringr::str_remove_all(Payment, '\\$|\\,')))
  •  Tags:  
  • Related