R-lang:如果等于引号,则删除第一个字符 [英] R-lang: remove first character if equal to quotation mark

查看:81
本文介绍了R-lang:如果等于引号,则删除第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R新手.我正在尝试从数据框中的行的开头和结尾删除".如果引号不是第一个或最后一个字符,我不想删除.我不确定为什么以下内容对我不起作用数据的数据框,其中每一行都是文本的数据点.

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'm not sure why the following is not working on my dataframe of data, where each line is a datapoint of text.

引号不是字符串,而是文本的一部分.

The quotations are not due to being a character string, but are a part of the text.

数据框的一行看起来像这样:

a line of the dataframe looks something like this:

x<-  '"hello world. She said, "hello again" it was a pleasant response"'

结果应为:

x2 <- 'hello world. She said, "hello again" it was a pleasant response"'

我认为这会起作用:

gsub("\\n\"", "", df)

但是,这不起作用.有什么建议吗?

but, this doesn't work. Suggestions?

推荐答案

您可以像这样在字符串的末尾删除引号:

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;"

这篇关于R-lang:如果等于引号,则删除第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆