escaping - Escape single quote in R variables -
i have table names in 1 column. have r script read table , write.table csv file further processing. script barfs when writing table if encounters name apostrophe (single quote) character such "o'reilly" in matrix
library(rcurl) library(rjsonio) dir <- "c:/users/rob/data" setwd(dir) filename <- "employees.csv" url <- "https://obscured/employees.html" html <- geturl(url, ssl.verifypeer = false) initdata <- gsub("^.*?emp.alleployeedata = (.*?);.*", "\\1", html) initdata <- gsub("'", '"', initdata) data <- fromjson( initdata ) table <- list() for(i in seq_along(data)) { job <- data[[i]][[1]] name <- data[[i]][[2]] age <- data[[i]][[6]] sex <- data[[i]][[7]] m <- matrix(nrow = 1, ncol = 4) colnames(m) <- c("job", "name", "age", "sex") m[1, ] <- c(job, name, age, sex) table[[i]] <- as.data.frame(m) write.table(table[[i]],file = filename,append = true,sep = ",",col.names = false,row.names = false) }
when encounter o'reilly, error receiving is:
error in m[1, ] <- c(job, name, age, sex) : number of items replace not multiple of replacement length
i end csv file includes data employees before o'reilly encountered. googling revealed people trying add quotes strings or parse strings containing escape characters.
is there way escape or remove single quotes inside data?
i replacing single quotes double quotes in line 11, don't need in data set. wasn't single quote in name messing things up, replacing single quote double messing things up.
removed line:
initdata <- gsub("'", '"', initdata)
Comments
Post a Comment