ShanZhengYang - 1 month ago 6x
R Question

# How to read "paired data" into an R data.table? Using an R list?

Let's say I have a

`data.table`
in R.

``````> library("data.table")
> DT = data.table(x=c("b","b","b","a","a","a"),v=rnorm(6))
> DT
x           v
1: b  0.77399102
2: b  0.71450334
3: b  0.07187842
4: a -0.88098815
5: a -0.90192891
6: a  0.66439642
``````

I supply a vector for the
`x`
field, and a vector for the
`v`
field, each with 6 items.

However, you see that I supply
`b`
three times, and
`a`
three times. This is a key-value pair, i.e.

``````'b' : '0.77399102', '0.71450334', '0.07187842'
'a' : '-0.88098815', '-0.90192891', '0.66439642'
``````

In R, one would implement this as a list, i.e.

``````pairs = list(b = c('0.77399102', '0.71450334', '0.07187842'),
a = c('-0.88098815', '-0.90192891', '0.66439642'))
``````

I would like to input the R list
`pairs`
into a
`data.table`
. Is this possible? I'm confused how to define the
`x`
and
`v`
fields with this object.

If this isn't possible, how would one do this?

Use `data.table(x = names(pairs), v = pairs)`. This also works with `data.frame`.