jay.sf
jay.sf

Reputation: 72633

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

Upvotes: 1

Views: 2634

Answers (4)

Antex
Antex

Reputation: 1444

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

Upvotes: 0

s_baldur
s_baldur

Reputation: 33498

So dput(x) is the correct answer but just in case you were wondering how to achieve this by modifying your existing code you could do something like the following:

cat(paste0('c("', paste(x, collapse='", "'), '")'))
c("c", "d", "b", "a", "e")

Can also be done with packages (as Tung has showed), here is an example using glue:

library(glue)
glue('c("{v}")', v = glue_collapse(x, '", "'))
c("c", "d", "b", "a", "e")

Upvotes: 3

InspectorSands
InspectorSands

Reputation: 2929

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

Upvotes: 1

Tung
Tung

Reputation: 28331

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

Upvotes: 2

Related Questions