如何去除外部引号并将其转换为R中的字符向量

huangapple go评论57阅读模式
英文:

How to remove outer quotes and transform it into a character vector in R

问题

var1 <- ""'A', 'B', 'C', 'D', 'E', 'F', 'F', 'G'""
var2 <- c('A', 'B', 'C', 'D', 'E', 'F', 'F', 'G')

英文:

I have an example character (not sure what exactly format it is called) that appears as:

var1 &lt;- &quot;&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;F&#39;, &#39;G&#39;&quot;

I wonder how do I remove the outer double quotes and transform it into a character vector that looks exactly like:

var2 &lt;- c(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;F&#39;, &#39;G&#39;)

that can be further used in creating data frames or plots, etc.?

答案1

得分: 4

你基本上有一个包含引号的CSV字符串。我喜欢scan函数的功能,因为它可以在一次操作中指定分隔符、输出类别、引号字符以及如何处理空格,从而更加清晰地处理这种情况:

var2 <- scan(text=var1, sep=",", what="", strip.white=TRUE)
# 读取了8个项目
var2
# [1] "A" "B" "C" "D" "E" "F" "F" "G"

输出的结构与您的期望完全一致:

dput(var2)
# c("A", "B", "C", "D", "E", "F", "F", "G")
英文:

You essentially have a string which is a quoted CSV. I like the functionality of scan for dealing with such circumstances cleanly, since you can specify separators, output class, quoting characters, and how to deal with white space all in one go:

var2 &lt;- scan(text=var1, sep=&quot;,&quot;, what=&quot;&quot;, strip.white=TRUE)
#Read 8 items
var2
#[1] &quot;A&quot; &quot;B&quot; &quot;C&quot; &quot;D&quot; &quot;E&quot; &quot;F&quot; &quot;F&quot; &quot;G&quot;

The output structure is exactly as you wished:

dput(var2)
#c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;F&quot;, &quot;G&quot;)

huangapple
  • 本文由 发表于 2023年6月13日 06:07:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定