Rushabh Patel
Rushabh Patel

Reputation: 2764

Convert each row of dataframe to new list in R

I have below sample input data-

> df <- data.frame(a=c(1,2,9),b=c(3,4,5),c=c(2,6,7))
> df
  a b c
1 1 3 2
2 2 4 6
3 9 5 7

I am trying to convert rach row into separate list.

My Attempt-

> apply(df,1,as.list)

The above solution converts each row into sublists. But, I am looking for 3 separate list in this case.

nrow(df) = no. of lists

Desired Output-

> list1
$a
[1] 1

$b
[1] 3

$c
[1] 2

> list2
$a
[1] 2

$b
[1] 4

$c
[1] 6

> list3
$a
[1] 9

$b
[1] 5

$c
[1] 7

Upvotes: 0

Views: 50

Answers (1)

markus
markus

Reputation: 26373

You can use by and as.list

out <- by(df, 1:nrow(df), as.list)
out
#1:nrow(df): 1
#$a
#[1] 1
#
#$b
#[1] 3

#$c
#[1] 2

#------------------------------------------------------------------------------ 
#1:nrow(df): 2
#$a
#[1] 2

#$b
#[1] 4

#$c
#[1] 6

#------------------------------------------------------------------------------
#1:nrow(df): 3
#$a
#[1] 9

#$b
#[1] 5

#$c
#[1] 7

That creates an object of class by. So you may call unclass(out) in the end.

Upvotes: 1

Related Questions