I have a numeric vector, one, which I'm trying to turn into a character vector where each element is separated by commas.
> one = c(1:5) > paste(as.character(one), collapse=", ") [1] "1, 2, 3, 4, 5" > paste(as.character(one), sep="' '", collapse=", ") [1] "1, 2, 3, 4, 5"
However, I want the output to look like:
"1", "2", "3", "4", "5"
Am I missing some parameter from the paste function? Help!?
A comma-separated list is produced for a structure array when you access one field from multiple structure elements at a time. For instance if S is a 5-by-1 structure array then S.name is a five-element comma-separated list of the contents of the name field.
Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.
shQuote
is probably the best way to do this. Specifically, this gets you the output you want:
cat(paste(shQuote(one, type="cmd"), collapse=", "))
If single quotes are fine, you can use:
paste(shQuote(one), collapse=", ")
type="cmd"
actually provides escaped quotes, which is what's actually useful for most contexts, but if you really want to display it somewhere with unescaped quotes, cat
provides that.
You say you want a character vector with that output, but others who find this question may be looking for one of these functions instead:
First, a way to get output ready for input to R; that would be dput
:
> dput(as.character(one)) c("1", "2", "3", "4", "5")
Second, a way to output a csv file, which would be write.csv
or write.table
. These functions take a parameter file
, not used here, to directly output to a file.
> write.table(matrix(as.character(one),nrow=1), sep=",", row.names=FALSE, col.names=FALSE) "1","2","3","4","5" > write.csv(matrix(as.character(one),nrow=1),row.names=FALSE) "V1","V2","V3","V4","V5" "1","2","3","4","5"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With