Yu Deng
Yu Deng

Reputation: 1061

R - combine a 3D matrix and single vector then select certain month data

i am now having a single date vector A (362 rows) and i have a 3D matrix B (dimensions 360*180*3620)

> str(ssta_date)
 POSIXlt[1:362], format: "1981-11-15" "1981-12-15" "1982-01-15" "1982-02-15" "1982-03-15" ...

> dim(ssta_sst)
[1] 360 180 362

is it possible to combine A and B as a data frame or something else. it must match each date and each temperature in the B [,,362]. so each date will corresponding to a 360*180 matrix.

Because i am planning to do this t to select certain month data, is there any shortcut to do month data selection without combine the two data sets?

Upvotes: 0

Views: 936

Answers (1)

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32351

If I understand what you want, you can use melt to convert your array to a data.frame, and then use merge to join it with the other piece of data. If you want an array at the end, you can use acast to convert the data.frame back to an array.

# Sample data
n <- 10
d <- array( 
  rnorm(n^3),
  dim = c(n,n,n), 
  dimnames = list(
    One   = LETTERS[1:n], 
    Two   = LETTERS[1:n], 
    Three = LETTERS[1:n]
  ) 
)
x <- data.frame( One=LETTERS[1:n], x=runif(n) )

library(reshape2)
d <- melt(d)
d <- merge( d, x, by="One", all=TRUE )
d$result <- d$value + d$x # Do something with the data
acast( d, One ~ Two ~ Three, value.var="result" )

Upvotes: 1

Related Questions