2012-12-20 61 views
4

如果xmpl列表矩陣操作是,其中每個元素具有整數age和列表data,其中data含有相同大小的三個矩陣,ac組合和上兩次嵌套在

什麼是最好的一個列表方式做

cor(xmpl[[:]]$data[[:]][c('a','b','c')], xmpl[[:]]$age) 

其中該結果將是3 x length(a)數組或列表反映與每個元素的每個實例相關聯age 210(行1),b(行2)和c(行3)橫跨xmpl


我正在閱讀代表不同管道輸出的矩陣。每個科目有3個科目和很多科目。目前,我已經創建了一個主題列表,其中包括管道矩陣列表。

的結構是這樣的:

str(exmpl) 
$ :List of 4 
    ..$ id  : int 5 
    ..$ age  : num 10 
    ..$ data  :List of 3 
    .. ..$ a: num [1:10, 1:10] 0.782 1.113 3.988 0.253 4.118 ... 
    .. ..$ b: num [1:10, 1:10] 5.25 5.31 5.28 5.43 5.13 ... 
    .. ..$ c: num [1:10, 1:10] 1.19e-05 5.64e-03 7.65e-01 1.65e-03 4.50e-01 ... 
    ..$ otherdata: chr "ignorefornow" 
    #[...] 

我想在所有科目與科目的年齡a每個元素相關。然後針對bc執行相同操作,並將結果放入列表中。

我想我正以一種尷尬的方式處理這個問題。我對存儲和檢索這些數據的「R方式」感興趣。

Data Structure and desired output http://dl.dropbox.com/u/56019781/linked/struct-2012-12-19.svg

library(plyr) 

## example structure 
xmpl.mat <- function(){ matrix(runif(100),nrow=10) } 
xmpl.list <- function(x){ list( id=x, age=2*x, data=list( a=x*xmpl.mat(), b=x+xmpl.mat(), c=xmpl.mat()^x ), otherdata='ignorefornow') } 
xmpl  <- lapply(1:5, xmpl.list) 

## extract 
ages <- laply(xmpl,'[[','age') 
data <- llply(xmpl,'[[','data') 

# to get the cor for one set of matrices is easy enough 
# though it would be nice to do: a <- xmpl[[:]]$data$a 
x.a  <- sapply(data,'[[','a') 
x.a.corr <- apply(x.a,1,cor,ages) 

# ... 

#xmpl.corr <- list(x.a.corr,x.b.corr,x.c.corr) 

# and by loop, not R like? 
xmpl.corr<-list() 
for (i in 1:length(names(data[[1]]))){ 
    x <- sapply(data,'[[',i) 
    xmpl.corr[[i]] <- apply(x,1,cor,ages) 
} 
names(xmpl.corr) <- names(data[[1]]) 

最終輸出:

str(xmpl.corr) 
List of 3 
$ a: num [1:100] 0.712 -0.296 0.739 0.8 0.77 ... 
$ b: num [1:100] 0.98 0.997 0.974 0.983 0.992 ... 
$ c: num [1:100] -0.914 -0.399 -0.844 -0.339 -0.571 .. 
+0

您能否詳細說明「跨科目年齡的所有科目」。另外,也許是'dput(xmpl)'? –

+0

@RicardoSaporta可以使用提供的代碼創建對象'xmpl'。 –

+0

哎呀!我錯過了最後的部分,我的錯誤 –

回答

3

這裏有一個解決方案。它應該足夠短。

​​3210
+0

這很酷。這是一個unlist + split的新奇用法,還是我應該認爲是慣用R的東西? – Will

+0

@Will對我來說你的任務看起來很特別。因此,在這種情況下使用「unlist」(將多個矩陣轉換爲一個向量)似乎是意想不到的。但是這裏「分裂」的用法是慣用的。 –

1

而不是x.a,x.b,x.c你可能想把所有這些都放在一個列表中。

# First, get a list of the items in data 
     abc <- names(xmpl[[1]]$data) # incase variables change in future 
names(abc) <- abc # these are the same names that will be used for the final list. You can use whichever names make sense 


## use lapply to keep as list, use sapply to "simplify" the list 
x.data.list <- lapply(abc, function(z) 
        sapply(xmpl, function(xm) c(xm$data[[z]]))) 

ages <- sapply(xmpl, `[[`, "age") 

# Then compute the correlations. Note that on each element of x.data.list we are apply'ing per row 
correlations <- lapply(x.data.list, apply, 1, cor, ages)