'How to paste vector elements comma-separated and in quotation marks?

I want to select columns of data frame dfr by their names in a certain order, that i obtain with the numbers in first place.

> (x <- names(dfr)[c(3, 4, 2, 1, 5)])
[1] "c" "d" "b" "a" "e"

In the final code there only should be included the names version, because it's safer.

dfr[, c("c", "d", "b", "a", "e")

I want to paste the elements separated with commas and quotation marks into a string, in order to include it into the final code. I've tried a few options, but they don't give me what I want:

> paste(x, collapse='", "')
[1] "c\", \"d\", \"b\", \"a\", \"e"
> paste(x, collapse="', '")
[1] "c', 'd', 'b', 'a', 'e"

I need something like "'c', 'd', 'b', 'a', 'e'",—of course "c", "d", "b", "a", "e" would be much nicer.

Data

dfr <- setNames(data.frame(matrix(1:15, 3, 5)), letters[1:5])


Solution 1:[1]

Try vector_paste() function from the datapasta package

library(datapasta)

vector_paste(input_vector = letters[1:3])
#> c("a", "b", "c")

vector_paste_vertical(input_vector = letters[1:3]) 
#> c("a",
#>   "b",
#>   "c")

Solution 2:[2]

Or, using base R, this gives you what you want:

(x <- letters[1:3])
q <- "\""
( y <- paste0("c(", paste(paste0(q, x, q), collapse = ", ") , ")" ))
[1] "c(\"a\", \"b\", \"c\")"

Though I'm not realy sure why you want it? Surely you can simply subset like this:

df <- data.frame(a=1:3, b = 1:3, c = 1:3)
df[ , x]

  a b c
1 1 1 1
2 2 2 2
3 3 3 3

df[ , rev(x)]

  c b a
1 1 1 1
2 2 2 2
3 3 3 3

Solution 3:[3]

suppose you want to add a quotation infront and at the end of a text, and save it as an R object - use the capture.output function from utils pkg.

Example. I want ABCDEFG to be saved as an R object as "ABCDEFG"

> cat("ABCDEFG")  
>     ABCDEFG
> cat("\"ABCDEFG\"")
>     "ABCDEFG"
> 

#To save output of the cat as an R object including the quotation marks at the start and end of the word use the capture.ouput

> add_quote <- capture.output(cat("\"ABCDEFG\""))
> add_quote
    [1] "\"ABCDEFG\""

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tung
Solution 2 InspectorSands
Solution 3 Antex