How to assign the output of dput() into an object or insert the double quote and then comma after every words?

207 Views Asked by At

I have a data frame like that:

x <- data.table(c('ACCN-NJ-A55O-01A-11D-A25L-08','ACCN-NJ-A55O-11D-11D-A25L-08', 'ACCN-05-4249-01A-01D-1105-08', 'ACCN-S2-AA1A-15C-12D-A397-08'))

Now I want to put every word inside the double quote and then place a comma. I tried dput, cat, paste, etc but they return print instead of assigning to an object. I need to assign it to an object for copying it to the clipboard. I tried dput and dget

dput( x$V1, "names")
xx <- dget("names")
xxxx <- cat(paste0('"', paste(xx, collapse="\", \""), '"'))

It return the expected output like

"ACCN-NJ-A55O-01A-11D-A25L-08", "ACCN-NJ-A55O-11D-11D-A25L-08", "ACCN-05-4249-01A-01D-1105-08", "ACCN-S2-AA1A-15C-12D-A397-08"

but I want to assign it into an object. Any help would be appreciated. Thanks in advance

2

There are 2 best solutions below

10
Park On BEST ANSWER

write.table to clipboard works.

    write.table(t(as.vector(x)), "clipboard", row.names = FALSE, col.names = FALSE, sep = ",")

then ctrl+V to script returns

    "ACCN-NJ-A55O-01A-11D-A25L-08","ACCN-NJ-A55O-11D-11D-A25L-08","ACCN-05-4249-01A-01D-1105-08","ACCN-S2-AA1A-15C-12D-A397-08"

I'm not sure if this is what you wanted.

5
Ronak Shah On

You can use -

val <- sprintf('"%s"', x$V1)
val

#[1] "\"ACCN-NJ-A55O-01A-11D-A25L-08\"" "\"ACCN-NJ-A55O-11D-11D-A25L-08\""
#[3] "\"ACCN-05-4249-01A-01D-1105-08\"" "\"ACCN-S2-AA1A-15C-12D-A397-08\""

Note that R escapes " hence you see the quotes with backslash. The "real" string can be seen with cat.

cat(val)

"ACCN-NJ-A55O-01A-11D-A25L-08" "ACCN-NJ-A55O-11D-11D-A25L-08" 
"ACCN-05-4249-01A-01D-1105-08" "ACCN-S2-AA1A-15C-12D-A397-08"

If you want the output to be of length one comma-separated string use toString(val).