[R] Manipulating Arrays

baptiste auguie baptiste.auguie at googlemail.com
Sun Oct 11 11:38:20 CEST 2009


Hi,

the abind package can help you with the first query,

## add values
library(abind)
arr <- abind(arr,arr[1,,,] * 2 + 1,along=1)
dim(arr)

as for the second, maybe you can use negative indexing,

## remove values
arr <- arr[-2,,,]

HTH,

baptiste

2009/10/11 ampc <ampc2008 at gmail.com>:
>
> 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 =
> c("c1",
> "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 =
> c("d1",
> "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,
> -16L))
>
> library(reshape)
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list