Alan E
Alan E

Reputation: 400

How to create data table from vector with named values and keep the names?

I've got a vector with named values:

v = c(a = 10, b = 20)

I would like to create a data.table and preserve the names in a separate column.

Upvotes: 10

Views: 6565

Answers (1)

Alan E
Alan E

Reputation: 400

Here are couple ways to achieve that.

> v = c(a = 10, b = 20)

Use names() function:

> data.table(names = names(v), v)
   names  v
1:     a 10
2:     b 20

This seems to be the best option if the vector is already stored in a variable.

If vector comes from an expression, and you would rather not compute it twice or assign to a variable, you can use as.data.table() function:

> as.data.table(v, keep.rownames=TRUE)
   rn  v
1:  a 10
2:  b 20

Upvotes: 13

Related Questions