[R] Elementary questions about data structures
Adaikalavan Ramasamy
ramasamy at cancer.org.uk
Fri Aug 6 15:32:10 CEST 2004
You will have to sort out the list before assigning. I am not sure if
there is an auto-sort ability in any of the function. Try this :
list1 <- list(x=2, y=3)
list2 <- list(y=7, x=8)
out <- data.frame( matrix(NA, nc=2, nr=5) )
colnames(out) <- c("x", "y")
out[1, ] <- unlist( list1[ colnames(out) ] )
out[2, ] <- unlist( list2[ colnames(out) ] )
out
x y
1 2 3
2 8 7
3 NA NA
4 NA NA
5 NA NA
If you are expecting one single named variable in each case, then
unlist(list1)[ colnames(out) ] will also give you the same answer.
Please do use "<-" as the assignment operator instead of "=" which is
used in named arguments in function. Also note that it is difficult to
distinguish "S = l1" and "S = 11"
If you know the total number of rows, it is better to pre-allocate a
matrix/dataframe than to grow it on the fly. If all your data is
numeric, use a matrix instead.
On Fri, 2004-08-06 at 11:47, Ajay Shah wrote:
> Folks,
>
> 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
> done?
>
> 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,
More information about the R-help
mailing list