如何将R代码转换为字符串?
我想将如何将R代码转换为字符串?,r,R,我想将c('1','2','text')转换为只包含一个元素的字符向量c('1','2','text') 我试过这个: > quote(c('1','2', 'text')) c("1", "2", "text") 但是 这是: > toString(quote(c('1','2', 'text'))) [1] "c, 1, 2, text" 它删除了所有标点符号(而我希望保留完全相同的字符串)。deparse用于将表达式转换为字符串 deparse(c('1','2', 'te
c('1','2','text')
转换为只包含一个元素的字符向量c('1','2','text')
我试过这个:
> quote(c('1','2', 'text'))
c("1", "2", "text")
但是
这是:
> toString(quote(c('1','2', 'text')))
[1] "c, 1, 2, text"
它删除了所有标点符号(而我希望保留完全相同的字符串)。
deparse
用于将表达式转换为字符串
deparse(c('1','2', 'text'))
#[1] "c(\"1\", \"2\", \"text\")"
cat(deparse(c('1','2', 'text')))
#c("1", "2", "text")
gsub("\"", "'", deparse(c('1','2', 'text')))
#[1] "c('1', '2', 'text')"
deparse(quote(c('1','2', 'text')))
#[1] "c(\"1\", \"2\", \"text\")"
另请参见替换
deparse(substitute(c(1L, 2L)))
#[1] "c(1L, 2L)"
你可以试试这个:
convert_vecteur <- function(vector){
if(is.numeric(vector)){
char<- paste0("c(",paste(vector,collapse = ","),")")
} else {
char <- paste0("c('",paste(vector,collapse = "','"),"')")
}
return(char)
}
convert_vecteur(c('1','2', 'text'))
#[1] "c('1', '2', 'text')"
cat(convert_vecteur(c('1','2', 'text')))
# c('1', '2', 'text')
convert\u vecteur同时使用cat
和deparse
是明智的选择。谢谢。我肯定会使用我的示例,但不会使用这个gsub(\“”,“””),deparse(c(1L,2L))
@d.b,它返回[1]“c('1','2')”
,而我期望[1]“c(1L,2L)”
谢谢,在我看来,gsub(\“”,“,“,”,deparse(替代品(c(1L,2L))
是最普遍的(在我的原始代码中,我有一堆不同的向量)。
convert_vecteur <- function(vector){
if(is.numeric(vector)){
char<- paste0("c(",paste(vector,collapse = ","),")")
} else {
char <- paste0("c('",paste(vector,collapse = "','"),"')")
}
return(char)
}
convert_vecteur(c('1','2', 'text'))
#[1] "c('1', '2', 'text')"
cat(convert_vecteur(c('1','2', 'text')))
# c('1', '2', 'text')