Home > Software engineering >  R import txt file with read.table when there are apostrophes
R import txt file with read.table when there are apostrophes

Time:02-25

I have a txt file containing these values:

id,value
001,'Mary'
002,'Mary's husband'

When reading in R with read.table, you see there will be a bug with 'Mary's husband' since there is an apostrophe.

How could we import the data in this case?

CodePudding user response:

Read the data in with read.csv as usual and then remove the apostrophes.

txt <- "
id,value
001,'Mary'
002,'Mary's husband'"

df1 <- read.csv(textConnection(txt))
df1$value <- gsub("^'|'$", "", df1$value)
df1
#>   id          value
#> 1  1           Mary
#> 2  2 Mary's husband

Created on 2022-02-24 by the reprex package (v2.0.1)

  • Related