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.
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.
Each row of a table is called a data record.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With