To avoid looping through lines, you can use this:
do.call(paste, c(lapply(names(d), function(n)paste0(n,"_",d[[n]])), sep="_"))
Benchmarking:
N <- 1e4 d <- data.table(a=runif(N),b=runif(N),c=runif(N),d=runif(N),e=runif(N)) f1 <- function(d) { do.call(paste, c(lapply(names(d), function(n)paste0(n,"_",d[[n]])), sep="_")) } f2 <- function(d) { apply(d, 1, function(x) paste(names(d), x, sep="_", collapse="_")) } require(microbenchmark) microbenchmark(f1(d), f2(d))
Note: f2 inspired by @Ricardo's answer.
Results:
Unit: milliseconds expr min lq median uq max neval f1(d) 195.8832 213.5017 216.3817 225.4292 254.3549 100 f2(d) 418.3302 442.0676 451.0714 467.5824 567.7051 100
Edit note: the previous benchmarking with N <- 1e3 did not show much time difference. Thanks again @eddi.
source share