kukuk1de kukuk1de - 25 days ago 8
R Question

paste columns where collapse parameter depends on column class

I'm trying to find a solution to paste all columns of a data table where the "collapse" parameter is set depending on the column class.

Example data:

DT <- data.table(Char1 = c('a','b','c','d'),
Int1 = c(1:4),
Char2 = c('e','f','g','h'),
Int2 = c(5:8))

sapply(DT, class)
Char1 Int1 Char2 Int2
"character" "integer" "character" "integer"

The result needed would be something like this:
Character, POSIX etc. wrapped in quotes but integers, numeric not.

"'a', 1, 'e', 5"
"'b', 2, 'f', 6"
"'c', 3, 'g', 7"
"'d', 4, 'h', 8"

As a background info...
I want to use this to generate SQL insert statements with correct syntax based on variable classes.

Answer Source

If s is the output of the sapply in the question then:

fmt <- toString(ifelse(s == "character", "`%s`", "%d"))
DT[, do.call("sprintf", cbind(fmt, .SD))]


[1] "`a`, 1, `e`, 5" "`b`, 2, `f`, 6" "`c`, 3, `g`, 7" "`d`, 4, `h`, 8"

This variation also works:

do.call("sprintf", cbind(fmt, DT))