Define a data.table from two string lists

Hello everyone,

I have the following two structures:

str(cl)

chr [1:5] "timestamp" "assess" "catheter" "service" "ref"

str(rw)

chr [1:5] "1654508112" "3" "gel" "2785" “16545081121a8d8f956cb871053a3f56b782b70a76"

From which I would like to generate a 5 col x 1 row data.table; the question is ‘how’?

‘cl’ represents the column names; ‘rw’ the row values.

With anticipatory thanks …
John

There may well be a more elegant solution but this gets to the goal.

library(data.table)
rw <- c("1654508112", "3", "gel", "2785", "16545081121a8d8f956cb871053a3f56b782b70a76")
DAT <- matrix(rw,ncol=5)
cl <- c("timestamp", "assess", "catheter", "service", "ref")
dimnames(DAT) <- list("",cl)
DAT <- as.data.table(DAT)
str(DAT)
Classes ‘data.table’ and 'data.frame':	1 obs. of  5 variables:
 $ timestamp: chr "1654508112"
 $ assess   : chr "3"
 $ catheter : chr "gel"
 $ service  : chr "2785"
 $ ref      : chr "16545081121a8d8f956cb871053a3f56b782b70a76"
 - attr(*, ".internal.selfref")=<externalptr> 

I admit its odd looking but here is a one liner ....

DAT <-`names<-`(data.table(rbind(rw)), cl)
1 Like

Many, many thanks for your solution; it is appreciated.
John

Many thanks for your reply; I like your style of coding ….
John

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.