4

ifxmplは、各要素が整数ageを持つリストと、同じサイズの3つの行列を含むリストdataです。dataac

最善の方法は何ですか

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

ここで、結果は、 (行1)、(行2)、および(行3) の各要素の各インスタンスとの相関を3 x length(a)反映する配列またはリストに なります。 ageabcxmpl


さまざまなパイプラインの出力を表すマトリックスを読み取っています。科目ごとに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すべての被験者のすべての要素を被験者の年齢と相関させたいと思います。次に、とについても同じことをb行いc、結果をリストに入れます。

私はRにとって厄介な方法でこれに取り組んでいると思います。このデータを保存および取得する「Rの方法」がどうなるかに興味があります。

データ構造と必要な出力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 ..
4

2 に答える 2

3

これが解決策です。それは十分に短いはずです。

ages <- sapply(xmpl, "[[", "age")                      # extract ages
data <- sapply(xmpl, function(x) unlist(x[["data"]]))  # combine all matrices
corr <- apply(data, 1, cor, ages)                      # calculate correlations
xmpl.corr <- split(corr, substr(names(corr), 1, 1))    # split the vector
于 2012-12-20T20:09:21.770 に答える