Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function for converting data.table to named list of named vectors

Tags:

r

data.table

I am looking for R function that in sensible time would convert a data.table for example (in real with many 1000s entries):

id num1 name
id1    1    a
id1    5    f
id1    8    y
id1    5    z
id2    2    w
id2    5    k
id2    6    l

to a named list by 'id' column of named by 'name' column vector of 'num1' column.

Output (a list) would look like this:

$id1
   a f y z
   1 5 8 5
$id2
   w k l
   2 5 6

Thank you in advance for your help.

like image 642
fattel Avatar asked Oct 23 '25 16:10

fattel


1 Answers

You can split and use setNames to get named vector

lapply(split(df, df[[1]]), function(x) setNames(x$num1, x$name))

#$id1
#a f y z 
#1 5 8 5 

#$id2
#w k l 
#2 5 6 

Similarly as @StudidWolf suggests, we can also use by here.

by(df,df$id,function(x) setNames(x$num1,x$name))
like image 101
Ronak Shah Avatar answered Oct 25 '25 05:10

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!