2009-09-23 14 views
3

有沒有人有任何關於如何在R中編寫複雜表格的好主意?在R中編碼複雜表格的好方法?

恐怕我可能會在這個有點模糊,但我想建立一個腳本來創建一批類似於美國統計摘要一個複雜的表格。

例如爲:http://www.census.gov/compendia/statab/tables/09s0015.pdf

而且我想避免一大堆rbind和hbind語句。

SAS,我聽說過,有一個表創建說明語言;我想知道R是否有類似的功能?

謝謝!

回答

3

它看起來像你想對一些數據應用一些不同的計算,將它分組一個字段(在這個例子中,按狀態)?

有很多方法可以做到這一點。見this related question

你可以使用哈德利韋翰的reshape包(見reshape homepage)。舉例來說,如果你想要的平均,總和,計數應用於由值分組的一些數據的功能(這是沒有意義的,但它從重塑使用airquality數據):

> library(reshape) 
> names(airquality) <- tolower(names(airquality)) 
> # melt the data to just include month and temp 
> aqm <- melt(airquality, id="month", measure="temp", na.rm=TRUE) 
> # cast by month with the various relevant functions 
> cast(aqm, month ~ ., function(x) c(mean(x),sum(x),length(x))) 
    month X1 X2 X3 
1  5 66 2032 31 
2  6 79 2373 30 
3  7 84 2601 31 
4  8 84 2603 31 
5  9 77 2307 30 

或者你可以使用by()功能。指數將代表各州。在你的情況下,你可以應用你自己的函數來完成多個任務(取決於你的需要),而不是應用一個函數(例如mean):例如,function(x) { c(mean(x), length(x)) }。然後在輸出上運行do.call("rbind"(例如)。

此外,你可能會使用一個報告程序,如Sweave(與xtable)或Jeffrey Horner's brew package給予一定的考慮。有一個great post on the learnr blog about creating repetitive reports顯示如何使用它。

+0

只是一個快速的一句話 - 'each'照顧列名的還有:'投(AQM,月〜,每個(平均,總和,長度)'和。 ,最簡單的就是用'c':'cast(aqm,month〜。,c(mean,sum,length)' – learnr 2009-10-01 21:55:47

1

另一種選擇是plyr包。

library(plyr) 
names(airquality) <- tolower(names(airquality)) 
ddply(airquality, "month", function(x){ 
    with(x, c(meantemp = mean(temp), maxtemp = max(temp), nonsense = max(temp) - min(solar.r))) 
}) 
0

Here is an interesting blog posting on this topic.作者試圖創建一個類似於聯合國的「世界人口前景:2008年修訂報告」的報告。

希望幫助, 查理

+0

查理:這不是我的答案底部的那個相同的鏈接嗎? – Shane 2009-10-01 19:53:09

+0

嗨謝恩,你'對,我很抱歉,我沒有注意到你的鏈接。 – Charlie 2009-10-01 20:14:12