Data.table: Proper way to turn a vector or a string into multi-column data.table

Created on 25 Nov 2019  路  1Comment  路  Source: Rdatatable/data.table

Hello data.table team,

What is the proper way to turn a vector or a string into a multi-column data.table?

Here's one way:
## vector to data.table
> d <- rbindlist(list(lapply(c("1","2","3"),c)))
> d
V1 V2 V3
1: 1 2 3

## string to data.table
> a <- "1,2,3"
> d <- rbindlist(lapply(a,tstrsplit,split=","))
> d
V1 V2 V3
1: 1 2 3

Is this the best way?

question

Most helpful comment

```{r}
vec <- letters
as.data.table(as.list(vec))

vec2 <- setNames(letters, LETTERS)
as.data.table(as.list(vec2))
```

A slightly faster and more memory-efficient way is to replace as.data.table with setDT, e.g., setDT(as.list(vec)).

>All comments

```{r}
vec <- letters
as.data.table(as.list(vec))

vec2 <- setNames(letters, LETTERS)
as.data.table(as.list(vec2))
```

A slightly faster and more memory-efficient way is to replace as.data.table with setDT, e.g., setDT(as.list(vec)).

Was this page helpful?
0 / 5 - 0 ratings