I am learning R and have a tutorial that wants me to remove the percent sign. The code they want me to use is:

 chocolateData$Cocoa_Percent <- sapply(chocolateData$Cocoa_Percent, function(x) gsub("%", "", x))

My question pertains to what I may be typing wrong, or if there is a different way to do this with R?

  • $\begingroup$ your code is correct and works for me. can you give a simple example that is not working for you? > cd <- NULL > cd$c <- c('test1%', 'test2%') > cd <- as.data.frame(cd) > cd$c [1] test1% test2% > cd$c <- sapply(cd$c, function(x) gsub("%","",x)) > cd$c [1] "test1" "test2" $\endgroup$ – user3631804 Nov 23 '18 at 14:58
  • $\begingroup$ If you just want to remove the percent sign for a single column use gsub("%", "", chocolateData$Cocoa_Percent) $\endgroup$ – rcs Nov 23 '18 at 15:19
  • $\begingroup$ tried it, not working on my system. $\endgroup$ – Chris Kehl Nov 23 '18 at 15:57
  • $\begingroup$ chocolateData$Cocoa.Percent = as.numeric(gsub("[\\%,]", "", chocolateData$Cocoa.Percent)) $\endgroup$ – Chris Kehl Nov 23 '18 at 16:14

The following code worked, thanks for the assistance.

chocolateData$Cocoa.Percent = as.numeric(gsub("[\\%,]", "", chocolateData$Cocoa.Percent))


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.