【问题标题】:Turning a vector of values into a comma separated vector with quote around each [duplicate]将值向量转换为逗号分隔的向量,每个向量都带有引号 [重复]
【发布时间】:2016-09-16 19:39:07
【问题描述】:

我想得到结果,使其显示为:

"6","4","8"

或逗号

my_vector = base::unique(mtcars$cyl)
my_vector_quoted =paste(my_vector, sep=" ' ")

现在我如何得到中间的逗号?我尝试使用 sep = ' 重复此操作,但这不起作用。

有什么办法吗?

【问题讨论】:

    标签: r string paste


    【解决方案1】:

    假设输入x,这里有几种可能性:

    toString(shQuote(x, type = "cmd"))
    
    options(useFancyQuotes = FALSE)
    toString(dQuote(x))
    
    library(withr)
    with_options(c(useFancyQuotes = FALSE), toString(dQuote(x)))
    
    toString(sprintf('"%d"', x))
    
    paste(paste0('"', x, '"'), collapse = ", ")
    

    例如,

    x <- c(6, 4, 8)
    xs <- toString(shQuote(x, type = "cmd"))
    

    给予:

    > cat(xs, "\n")
    "6", "4", "8" 
    
    > strsplit(xs, "")[[1]] # shows that xs contains 13 characters
    [1] "\"" "6"  "\"" ","  " "  "\"" "4"  "\"" ","  " "  "\"" "8"  "\""
    

    【讨论】:

    • 很好的答案,但一定要包裹在cat 中以打印所需的输出(即“6”、“4”、“8”)
    【解决方案2】:

    你想要这个吗?

    my_vector_quoted =paste(my_vector, collapse=",")
    #"6,4,8"
    

    【讨论】:

    • 每个数字用引号和逗号分隔。这是一半。我认为上述解决方案可能有效。
    • my_vector_quoted = paste(my_vector, collapse='","'),输出 "6\",\"4\",\"8"
    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    相关资源
    最近更新 更多