0

I HAVE a dataframe named DF which has about 16 columns, out of which in 1 column named admit_dx, in which I would like to do string replacement by str_replace() from stringr package written below.

DF <- str_replace(DF$admit_dx, ';', '') 

The above statement does my job while other columns went away from the dataframe. Please, anyone can suggest how to retain other columns while making changes in one particular column of the dataframe? (Note: I don't want to the modified column with other unaffected columns into a separate dataframe).

ah bon
  • 9,293
  • 12
  • 65
  • 148

1 Answers1

0

In the tidyverse workflow use mutate from dplyr.

library(stringr)
library(dplyr)
DF <- DF %>%
  mutate(admit_dx=str_replace(admit_dx, ';',''))

Alternatively do this with gsub and transform in base R.

DF <- transform(DF, admit_dx=gsub(';','', admit_dx))

Or just

DF$admit_dx <- gsub(";", "", admit_dx)
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • Hi jay.sf!, thanks for looking in to the query.in adition to ; , i also have "?" as a special character at the starting point of the string. eg: ? PULMONARY EMBOLUS WITH DESATURATION . when i use transform or mutate function it doesn't work. any ideas why? – sitaram Jul 07 '20 at 07:00
  • @sitaram [Escape special characters using two backslashes](https://stackoverflow.com/q/27721008/6574038). You may put all your patterns into `[` `]`, try `trimws(gsub("[\\?;,]", "", "? PULMONARY; EMBOLUS, WITH DESATURATION"))`. The `trimws` removes whitespace. – jay.sf Jul 07 '20 at 07:22