2012-10-15 209 views
3

我有一個嵌套列表,而需要計算如何ddply嵌套列表

$`bs. bs` 
    fapp frt sapp srt 
1 bs 2280 bs 0.25 
2 bs 2287 bs 0.25 
3 bs 2288 bs 0.25 
4 bs 2289 bs 0.25 

$`bs. lhc` 
    fapp frt sapp  srt 
5 bs 2320 lhc 0.250000 
6 bs 2333 lhc 0.250214 
7 bs 2524 lhc 0.316449 

源FRT和SRT的相關性:

structure(list(`bs. bs` = structure(list(fapp = structure(c(1L, 
    1L, 1L, 1L), .Label = "bs", class = "factor"), frt = c(2280L, 
    2287L, 2288L, 2289L), sapp = structure(c(1L, 1L, 1L, 1L), .Label = c(" bs", 
    " lhc"), class = "factor"), srt = c(0.25, 0.25, 0.25, 0.25)), .Names = c("fapp", 
    "frt", "sapp", "srt"), row.names = c(NA, 4L), class = "data.frame"), 
    `bs. lhc` = structure(list(fapp = structure(c(1L, 1L, 1L), .Label = "bs", class=   "factor"), 
    frt = c(2320L, 2333L, 2524L), sapp = structure(c(2L, 
    2L, 2L), .Label = c(" bs", " lhc"), class = "factor"), 
    srt = c(0.25, 0.250214, 0.316449)), .Names = c("fapp", 
"frt", "sapp", "srt"), row.names = 5:7, class = "data.frame")), .Names = c("bs. bs", 
    "bs. lhc")) 

ddply(y,.(fapp + sapp),cor) 

ddply(y,.(fapp,sapp),cor) 

不起作用

+0

爲了得到最好的答案,請創建一個可重複的例子... –

回答

3
> ldply(y, function(x) { x$corr <- cor(x$frt, x$srt); x }) 
     .id fapp frt sapp  srt  corr 
1 bs. bs bs 2280 bs 0.250000  NA 
2 bs. bs bs 2287 bs 0.250000  NA 
3 bs. bs bs 2288 bs 0.250000  NA 
4 bs. bs bs 2289 bs 0.250000  NA 
5 bs. lhc bs 2320 lhc 0.250000 0.9985343 
6 bs. lhc bs 2333 lhc 0.250214 0.9985343 
7 bs. lhc bs 2524 lhc 0.316449 0.9985343 
Warning message: 
In cor(x$frt, x$srt) : the standard deviation is zero 
Calls: ldply -> llply -> structure -> lapply -> FUN -> cor 

或將結果保存爲一個列表

> llply(y, function(x) { x$corr <- cor(x$frt, x$srt); x }) 
$`bs. bs` 
    fapp frt sapp srt corr 
1 bs 2280 bs 0.25 NA 
2 bs 2287 bs 0.25 NA 
3 bs 2288 bs 0.25 NA 
4 bs 2289 bs 0.25 NA 

$`bs. lhc` 
    fapp frt sapp  srt  corr 
5 bs 2320 lhc 0.250000 0.9985343 
6 bs 2333 lhc 0.250214 0.9985343 
7 bs 2524 lhc 0.316449 0.9985343 

Warning message: 
In cor(x$frt, x$srt) : the standard deviation is zero 
Calls: llply -> structure -> lapply -> FUN -> cor 
1

你想用ldply,這在一個列表的元素應用於你的函數,那麼像您呼叫的第二個版本ddply應該工作。沒有示例數據,我無法證明它。

+0

你的意思是'ldply'可能:) 。儘管使用嵌套列表獲得相同的緊湊語法有點困難。 –

+0

你是對的,謝謝! – Charlie

1

ddply明確設計用於data.frame的工作。所以,我會先放列表中的所有元素在data.frame

dat = do.call("rbind", nested_list) 

然後用ddply

ddply(dat, .(fapp, sapp), corr)