简体   繁体   中英

R data.table: turn a vector into a one row data.table

I have a character vector x which I want to turn into a one row data.table in a speedy way. The command data.table(x) returns a one column data.table. Now, data.table(t(x)) gets the job done but I'm wondering if there's a faster way.

We could use

x <- 1:5
setDT(as.list(x))[]

Benchmarks

v1 <- 1:1e5
system.time(data.table(t(v1)))
#   user  system elapsed 
#  12.95    0.01   12.97 
system.time(setDT(as.list(v1)))
#  user  system elapsed 
#   5.75    0.00    5.75 

system.time(as.data.table(t(v1)))
#    user  system elapsed 
#   6.35    0.00    6.34 

Update

If the above exercise it to rbind a vector with a data.table , we dont need to convert the vector to data.table

 d1 <- data.table(V1= 1:3, V2= 4:6, V3=7:9)
 rbindlist(list(d1, as.list(1:3)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM