R:基于列值创建3D矩阵

时间:2013-02-18 00:34:28

标签: r multidimensional-array

我有一个矩阵,前面有两列:location,year。接下来是50列,每个日历日一列。如果没有访问过该位置,则天数列为“NA”,如果位置为,则为“1”。

示例:

Location Year 1  2  3  4  5  6  7 8  9  10 .... 50
Site1    2005 NA NA NA 1  NA NA 1 NA NA 1  .... NA
Site2    2006 NA NA 1  NA NA NA 1 NA NA 1  .... NA

我之前使用了reshape包来创建4维矩阵,数据框中的每一列都用作变量来融化然后再投射数组。但是在这里,我有多个列,它似乎也不起作用。

我想创建以下内容:

dim Y: locations
dim X: days 1-50
dim Z: Years

这几乎就像从每年提取数据,并将每个位置按天排列一个接一个。有谁知道以这种方式创建三维数组的最佳方法是什么?

感谢。

3 个答案:

答案 0 :(得分:0)

可能有一个更简洁的方法来处理reshape2库,但使用lapply将为您提供干净的列表。如果您需要它们作为数组,只需转换为

arr <- lapply(unique(dat$Location), function(L) dat[dat$Location==L, -1])

# add names, to keep it neat
names(arr) <- unique(dat$Location)

# Convert to array if needed
arr <- as.array(arr)

答案 1 :(得分:0)

目前尚不清楚你想要拥有什么(你给出了最终结果的一些价值,而不仅仅是结构,还有一些数据要处理)

首先我重现你的数据

dat <- data.frame(Location =c('Site1','Site2'),
           Year=c(2005,2006))
dat <- cbind(dat,matrix(sample(c(1,NA),100,rep=T),ncol=50))

然后使用reshape2我得到了这个:

library(reshape2)
melt(dat,id.vars=c('Location','Year'))
    Location Year variable value
1      Site1 2005        1    NA
2      Site2 2006        1    NA
3      Site1 2005        2     1
4      Site2 2006        2    NA
5      Site1 2005        3    NA
6      Site2 2006        3     1
7      Site1 2005        4     1
8      Site2 2006        4    NA

答案 2 :(得分:0)

我猜你要删除NAs。

library(reshape2)

test <- read.table(text="Location Year 1  2  3  4  5  6  7 8  9  10
Site1    2005 NA NA NA 1  NA NA 1 NA NA 1
Site2    2006 NA NA 1  NA NA NA 1 NA NA 1", h=T)

melt(test, id = c("Location", "Year"), na.rm = TRUE, variable.name = "day")[, -4]

#    Location Year  day
# 6     Site2 2006   X3
# 7     Site1 2005   X4
# 13    Site1 2005   X7
# 14    Site2 2006   X7
# 19    Site1 2005  X10
# 20    Site2 2006  X10