r
  • string
  • paste
  • 2016-09-16 86 views 1 likes 
    1

    周圍報價矢量我想得到的結果,使得其是顯示爲:車削值的向量成逗號分隔與每個

    「6」,「4」,「8」

    或逗號

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

    現在我該怎樣得到逗號之間?我試着用sep ='重複這個,但那不起作用。

    任何解決方法?

    回答

    6

    以下是假設輸入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" "\"" 
    
    +0

    好的答案,但一定要用'cat'打包來打印期望的輸出(即「6」,「4」,「8」) –

    1

    你想要這個嗎?

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

    由引號和逗號分隔每個號碼。這是一半。我認爲上述解決方案可能有效 – runningbirds

    +0

    my_vector_quoted = paste(my_vector,collapse ='「,」'),輸出爲 「6」,「4」,「8」 –

    相關問題