如何将R代码转换为字符串?

3
我希望将c('1','2', 'text')转换为只有一个元素的字符向量c('1','2', 'text')
我尝试过以下方法:
> quote(c('1','2', 'text'))
c("1", "2", "text")

但是。
> class(quote(c('1','2', 'text')))
[1] "call"

并且这个:

> toString(quote(c('1','2', 'text')))
[1] "c, 1, 2, text"

这个功能会去除所有标点符号(但我希望保留原始字符串)。

2个回答

8

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\")"

还需查看substitute

deparse(substitute(c(1L, 2L)))
#[1] "c(1L, 2L)"

1
catdeparse组合使用是明智的选择。 - M--
谢谢。这个代码片段对我的示例确实有效,但是对于这个 gsub("\"", "'", deparse(c(1L ,2L))) 却无效。 - Dambo
@d.b 返回 [1] "c('1', '2')", 但我期望的是 [1] "c(1L, 2L)" - Dambo
1
谢谢,对我来说 gsub("\"", "'", deparse(substitute(c(1L, 2L)))) 是最通用的(在我的原始代码中有很多不同的向量)。 - Dambo

2
你可以尝试以下方法:

  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')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接