[R] Create Arrays
Barry Rowlingson
b.rowlingson at lancaster.ac.uk
Fri Oct 15 11:05:57 CEST 2010
On Fri, Oct 15, 2010 at 9:55 AM, dpender <d.pender at civil.gla.ac.uk> wrote:
>
> Hi,
>
> For this example:
>
> O <- c(0 0 0 2 0 0 2 0)
>
> I want to create an array every time O[i] > 0. The array should be in the
> form;
>
> R[j] <- array(-1, dim=c(2,O[i]))
>
> i.e. if O[i] > 0 4 times I want 4 R arrays.
>
> Does anyone have any suggestions?
>
Suggestion number l is don't use O for objects! Far too confusing!
Serious suggestion is that a concrete example will help. Let me try:
If:
X = c(0,0,0,2,0,0,3,0) # I'm not using O here!
Then
R will be a list of length 2 because there are 2 values in X bigger than 0.
R[1] will be array(-1,dim=c(2,2)) # because X[4] is 2
and
R[2] will be array(-1,dim=c(2,3)) # because X[7] is 3
Yup?
Okay, first get rid of the zeroes:
Xnz = X[X!=0]
That simplifies the problem. Then use lapply to iterate over Xnz with
a function that returns the array given the value:
> lapply(Xnz,function(x){array(-1,dim=c(2,x))})
[[1]]
[,1] [,2]
[1,] -1 -1
[2,] -1 -1
[[2]]
[,1] [,2] [,3]
[1,] -1 -1 -1
[2,] -1 -1 -1
2-d arrays are just matrices, so you can do it all in one line with:
lapply(X[X!=0],function(x){matrix(-1,2,x)})
Barry
More information about the R-help
mailing list