Using Apply on a Multidimensional Array in R

Using apply on a multidimensional array in R

A.mean <- apply(A, c(1,2), mean)

Two-dimensional apply in R?

I'd suggest using expand.grid, which creates a "long form" of all 2-way combination, and then use mapply to create the values from the function:

chemArr = c("water","oil","hydrogen")
timeArr = c("0", "8hr", "12hr", "24hr", "36hr", "48hr", "72hr")
mygrid <- expand.grid(chemArr, timeArr)
mygrid <- expand.grid(chems = chemArr, times = timeArr)
str(mygrid)
#'data.frame': 21 obs. of 2 variables:
# $ chems: Factor w/ 3 levels "water","oil",..: 1 2 3 1 2 3 1 2 3 1 ...
# $ times: Factor w/ 7 levels "0","8hr","12hr",..: 1 1 1 2 2 2 3 3 3 4 ...
# - attr(*, "out.attrs")=List of 2
# ..$ dim : Named int 3 7
# .. ..- attr(*, "names")= chr "chems" "times"
# ..$ dimnames:List of 2
# .. ..$ chems: chr "chems=water" "chems=oil" "chems=hydrogen"
# .. ..$ times: chr "times=0" "times=8hr" "times=12hr" "times=24hr" ...

mygrid$f_value <- mapply(f, mygrid$chems, mygrid$times)


Related Topics



Leave a reply



Submit