英文:
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 <- "'A', 'B', 'C', 'D', 'E', 'F', 'F', 'G'"
I wonder how do I remove the outer double quotes and transform it into a character vector that looks exactly like:
var2 <- c('A', 'B', 'C', 'D', 'E', 'F', 'F', 'G')
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 <- scan(text=var1, sep=",", what="", strip.white=TRUE)
#Read 8 items
var2
#[1] "A" "B" "C" "D" "E" "F" "F" "G"
The output structure is exactly as you wished:
dput(var2)
#c("A", "B", "C", "D", "E", "F", "F", "G")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论