Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transform a vector and a list of lists into a data.frame in R?

Tags:

dataframe

r

Essentially I'm after the product of a vector and a list of lists where the LoL has arbitrary lengths.

dose<-c(10,20,30,40,50)  
resp<-list(c(.3),c(.4,.45,.48),c(.6,.59),c(.8,.76,.78),c(.9))

I can get something pretty close with

data.frame(dose,I(resp))

but it's not quite right. I need to expand out the resp column of lists pairing the values against the dose column.

The desired format is:

10 .3
20 .4
20 .45
20 .48
30 .6
30 .59
40 .8
40 .76
40 .78
50 .9
like image 739
user1616353 Avatar asked Aug 22 '12 08:08

user1616353


1 Answers

Here is a solution using rep() and unlist().

  • Use rep to repeat the elements of dose, with the length of each element of resp.
  • Use unlist to turn resp into a vector

The code:

data.frame(
  dose = rep(dose, sapply(resp, length)),
  resp = unlist(resp)
)

   dose resp
1    10 0.30
2    20 0.40
3    20 0.45
4    20 0.48
5    30 0.60
6    30 0.59
7    40 0.80
8    40 0.76
9    40 0.78
10   50 0.90
like image 179
Andrie Avatar answered Oct 13 '22 11:10

Andrie