9

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
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user1616353
  • 135
  • 7
  • 2
    Welcome to Stack Overflow! +1 for [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Andrie Aug 22 '12 at 09:28
  • Just to be certain: `dose` always has as many elements as there are list elements in `resp` ? And just out of interest, what do you plan to do with the output array? We might be able to suggest a "shortcut" to your ultimate requirement. – Carl Witthoft Aug 22 '12 at 12:36
  • @Carl Yes, the dose values are paired against the lists in the resp (response) list. There is just an unknown number of such pairings for each dosage. The output data.frame is used in drm for fitting a regression curve. I was doing something like `unlist(lapply(resp,mean))` but although this gets me the regression curve, it causes problems for `modelFit()`, I eventually found that I had to give the regression the raw values to get my goodness of fit statistics, hence the need to transform into raw dose/response pairs. – user1616353 Aug 23 '12 at 00:48
  • Err, that package should be library(drc). drm is the name of the regression fitting function. – user1616353 Aug 23 '12 at 00:54

1 Answers1

14

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
Andrie
  • 176,377
  • 47
  • 447
  • 496