# [R] Question on lists and vectors of lists

Thu Jun 17 19:46:11 CEST 2004

```Try this :

silly.fn <- function(x){ return( c(x^2, x^3) ) }

output <- matrix( nr=100, nc=2 )
for(i in 1:100){
my.x <- rnorm(1)
output[i, ] <- silly.fn( my.x )
rownames(output)[i] <- paste("Dataset", i, sep="")
}
colnames(output) <- c("squared", "cubed")

Notice that silly.fn returns a vector which is set to be the ith row of
output.

It is also possible to speed this with the apply family but this depends
on your input format. For example if your input was a list where the
first element corresponds to 1st company information in dataframe format

sapply( my.list.of.matrices, function(single.mat) some.fn(single.mat) )

Another option is to use output[i, ] <- unlist(think_one_firm("blah"))
where unlist hopefully will convert the list to vector.

On Thu, 2004-06-17 at 18:26, Ajay Shah wrote:
> I have an elementary programming question. Could someone please point
> me in the right direction?
>
> I have a function which will run for thousands of companies. At each
> invocation, it returns 2 numbers. I plan to do something like:
>
>   think_one_firm <- function(filename) {
>      # Do stuff
>      return(list(x=x,y=y))
>   }
>
> So for each of the firms in my dataset, I will call
> think_one_firm(datafilename) and it will give me back two numbers x
> and y. I could say:
>
>   l = think_one_firm("blah")
>   print(l\$x); print(l\$y);
>
> and all would be fine.
>
> What I want to do is: To tuck away the returned lists into a vector or
> a data frame.
>
> At the end, I would like to endup with a data structure allfirms
> containing one 'row' for each firm. I guess this could be a data
> frame, or a matrix, or a vector of lists (if such a thing exists). In
> case it's a data frame, I would say allfirms\$x to access the 'x'
> value returned for the 400th firm.
>
> How would I do this?

```