R-lang: remove first character if equal to quotation mark

后端 未结 1 1476
别那么骄傲
别那么骄傲 2021-01-15 03:57

R newbie. I am trying to remove the, \" from the beginning and end of a line in a dataframe. I do not want to remove if the quotation is not the first or last character. I\'

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 04:30

    you can trim a quotation mark from the end of the string like this:

    x <- gsub('"$','',x)
    

    and from the beginning of the string like this:

    x <- gsub('^"','',x)
    

    since the characters $ and ^ match the end and beginning of the string. For example:

    myData<-data.frame(foo=c('"asdf"','ASDF'),
                       bar=c('jkl;','"JKL;"'))
    myData
    #>     foo    bar
    #>1 "asdf"   jkl;
    #>2   ASDF "JKL;"
    
    # trim the quote characters from myData$foo
    myData$foo <- gsub("^\"|\"$", "", myData$foo)
    myData
    
    #>   foo    bar
    #>1 asdf   jkl;
    #>2 ASDF "JKL;"
    

    0 讨论(0)
提交回复
热议问题