[R] Elementary questions about data structures

Ajay Shah ajayshah at mayin.org
Fri Aug 6 12:47:40 CEST 2004


S_t = (x_t, y_t) is the state of a system at time t. There is an
iterative function which converts S_t into S_{t+1}. I can easily write
this in R like this:

       iterate <- function(S) {
         list(S$x+1, S$y+1)

So this function eats S_t and makes S_{t+1} and I can say
S2 <- iterate(S1)

My question: suppose I want to iterate from 1..10, what is the data
structure that is appropriate to store all these lists?

How, in R, does one make "vectors of lists"? I want to think of the
state vector at time t as a "record" and then I want to have a
vectorfull of them. When I'm done, I want to be able to make pictures
of the time-series of S$x and the time-series of S$y. How is this

I tried some things:

> l1=list(x=2,y=3)
> l2=list(y=7,x=8)              # <--  note the order
> S = data.frame(x=1,y=1)       # odd way of initialising initial state
> S[2,] = l1
> S[3,] = l2
> S
  x y
1 1 1
2 2 3
3 7 8                           # <-- note it came out wrong.

I was very puzzled that he was wrong in how he handled the l2
assignment. How is it that the order matters? I thought lists were
handled in a more abstract way, where R knows that l2 is a collection
of l2$x and l2$y, without concern about the order in which they came
in. I had hoped that he would see that in S, there is an x and a y,
and that he would marry things up correctly. He doesn't.

What I would like to do is something like this:

S[1,] = list(x=1,y=2)                     # line 1
for (i in 2:10) {
  S[i,] = iterate(S[(i-1),])

I get errors at line 1 saying Error: Object "S" not found

If this could work, I know I'd be able to happily deal with the
time-series vector S$x and the time-series vector S$y.

Thanks a lot,

Ajay Shah                                                   Consultant
ajayshah at mayin.org                      Department of Economic Affairs
http://www.mayin.org/ajayshah           Ministry of Finance, New Delhi

More information about the R-help mailing list