[R] Question on lists and vectors of lists

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Thu Jun 17 20:04:35 CEST 2004


On Thu, 17 Jun 2004 22:56:29 +0530 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[400] to access the 'x'
> value returned for the 400th firm.
> 
> How would I do this?

If I understand correctly what you are trying to do, you could do the
following:

Suppose you have some firms:

firms <- c("blah", "foo", "bar")

and a function which computes something based on these firms

thinkOneFirm <- function(firm) list(x = rnorm(1), y = rnorm(1))

(which for this example just returns random numbers, but let's imagine
it's something more sensible :))

And then 

rval1 <- sapply(firms, thinkOneFirm)

gives you a matrix with the numeric results. To get the desired
data.frame you need to transpose and coerce

rval2 <- as.data.frame(t(rval1))

and then you can get value x for firm "foo" by

rval2$x["foo"]

or

rval2["foo", "x"]

hth,
Z

> -- 
> Ajay Shah                                                   Consultant
> ajayshah at mayin.org                      Department of Economic Affairs
> http://www.mayin.org/ajayshah           Ministry of Finance, New Delhi
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list