[R] Manipulating Arrays

ampc ampc2008 at gmail.com
Sun Oct 11 00:50:53 CEST 2009

Manipulating Arrays
Using the below data:

df <- structure(list(dim1 = structure(c(1L, 3L, 1L, 4L, 1L, 2L, 2L, 
2L, 3L, 1L, 4L, 3L, 4L, 4L, 3L, 2L), .Label = c("a1", "a2", "a3", 
"a4"), class = "factor"), dim2 = structure(c(2L, 1L, 2L, 2L, 
4L, 3L, 1L, 3L, 1L, 3L, 2L, 4L, 3L, 4L, 1L, 4L), .Label = c("b1", 
"b2", "b3", "b4"), class = "factor"), dim3 = structure(c(1L, 
4L, 3L, 2L, 1L, 1L, 2L, 4L, 3L, 2L, 2L, 3L, 3L, 1L, 4L, 4L), .Label =
"c2", "c3", "c4"), class = "factor"), dim4 = structure(c(2L, 
4L, 1L, 3L, 3L, 1L, 2L, 2L, 3L, 2L, 3L, 4L, 1L, 4L, 1L, 4L), .Label =
"d2", "d3", "d4"), class = "factor"), value = c(33L, 28L, 97L, 
64L, 95L, 64L, 21L, 76L, 93L, 50L, 30L, 7L, 89L, 57L, 27L, 14L
)), .Names = c("dim1", "dim2", "dim3", "dim4", "value"), class =
"data.frame", row.names = c(NA, 

arr <- cast(df, dim1~dim2~dim3~dim4, sum)

> dim(arr)
[1] 4 4 4 4

How do I manipulate this array?

1. Can I add an extra element in the first dimension using the existing
dimensions? As in a dataframe? Such as (The below does not work)

> arr[5,,,] <- arr[1,,,] * 2 + 1 
Error in arr[5, , , ] <- arr[1, , , ] * 2 + 1 : subscript out of bounds

2. How do I remove say the 2 element of the first dimension and have other
elements re-arranged in the logical way 
i.e deleting arr[2,,,] means arr[3,,,] becomes arr[2,,,]; and arr[4,,,]
becomes arr[3,,,]
(again the below does not work)
arr[2,,,] <- NULL

Error in arr[2, , , ] <- NULL : 
  number of items to replace is not a multiple of replacement length

View this message in context: http://www.nabble.com/Manipulating-Arrays-tp25838608p25838608.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list