Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

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.

like image 842
Alan E Avatar asked Apr 27 '16 00:04

Alan E


People also ask

How do you create a data table in R?

We can create a table by using as. table() function, first we create a table using matrix and then assign it to this method to get the table format. Example: In this example, we will create a matrix and assign it to a table in the R language.

What are the other name's of a row in a data table?

Each row of a table is called a data record.


1 Answers

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
like image 137
Alan E Avatar answered Sep 28 '22 19:09

Alan E