Search code examples
rurldata-manipulationquotesdouble-quotes

R: automatically adding quotes infront and behind text


I am working with the R programming language. I have a data frame called "a" with a single column called "V1". Each entry in "a" is a URL link in the following format:

 1 https:blah-blah-blah.com/item/123/index.do
 2 https:blah-blah-blah.com/item/124/index.do
 3 https:blah-blah-blah.com/item/125/index.do

I am trying to add double quotes (i.e " ") in front of and behind each of these items, so they look like this:

 1 "https:blah-blah-blah.com/item/123/index.do"
 2" https:blah-blah-blah.com/item/124/index.do"
 3 "https:blah-blah-blah.com/item/125/index.do"

Using this previous stackoverflow post (How to add quotes around each word in a string in R? ) , I tried the following code:

new_file = cat(gsub("\\b", '"',a$V1, perl=T))

and

new_file = cat(gsub("(\\w+)", '"\\1"', a$V1))

But these are not producing the intended results. Can someone please show me what I am doing wrong?

Thanks


Solution

  • In my humble opinion paste0 should do the job.

    • Actually " & ' do the same job but act differently when used simultaneously. See the two cases below-

    case-1

    a <-  data.frame(V1 = c('https:blah-blah-blah.com/item/123/index.do',
                            'https:blah-blah-blah.com/item/124/index.do',
                            'https:blah-blah-blah.com/item/125/index.do'))
    
    a
                                              V1
    1 https:blah-blah-blah.com/item/123/index.do
    2 https:blah-blah-blah.com/item/124/index.do
    3 https:blah-blah-blah.com/item/125/index.do
    
    a$V1 <- paste0('"', a$V1, '"')
    a
    
                                                V1
    1 "https:blah-blah-blah.com/item/123/index.do"
    2 "https:blah-blah-blah.com/item/124/index.do"
    3 "https:blah-blah-blah.com/item/125/index.do"
    

    case-2

    a <-  data.frame(V1 = c("https:blah-blah-blah.com/item/123/index.do",
                            "https:blah-blah-blah.com/item/124/index.do",
                            "https:blah-blah-blah.com/item/125/index.do"))
     
    a
                                              V1
    1 https:blah-blah-blah.com/item/123/index.do
    2 https:blah-blah-blah.com/item/124/index.do
    3 https:blah-blah-blah.com/item/125/index.do
    
    a$V1 <- paste0("'", a$V1, "'")
    a
                                                V1
    1 'https:blah-blah-blah.com/item/123/index.do'
    2 'https:blah-blah-blah.com/item/124/index.do'
    3 'https:blah-blah-blah.com/item/125/index.do'