chainsawriot

Home | About | Archive

現實的 R: DESCRIPTIVE STATISTICS 後續

Posted on Apr 29, 2011 by Chung-hong Chan

感謝讀者 Paladinoflab 提供了刪除 X1, X2, X3 的方法。跟據他提供的方法,我再想出更好的解決方案。
由於例子中的 table1 的第一行資料 (即 table1[1,]) 才是想用來當輸出 table 的第一行,故此要做以下的東西:

1. 將 table1[1,] 的資料變成 column name
2. 刪去 table[1,]

另外,其於 t() 的限制,要用到 data.frame(t()) 這樣樣衰的組合。 (( t 原意是用於 matrix ,但亦可用於 data frame 。但是會先將 data frame 轉成 matrix 再 transpose ,出來的結果是 matrix 。之後又要轉回 data frame ))
寫了個叫 doBy.t() 的東西去做 abstraction ((讀左皮毛 computer science 就扮 Q 晒野講術語,仲要唔知o岩唔o岩。)) ,專用於改變 summaryBy() 製出來的 data frame 。

#< -
doBy.t <- function (df.doBy) {
  ## to transpose the dataframe generated by summaryBy and replace
  ## the colnames with the names in 1st row
  temp.df <- data.frame(t(df.doBy))
  ## don't know why temp.df[1,] doesn't work as vector for colname
  ## do it raw
  realcolname <- c()
  for (i in 1:length(temp.df[1,])) {
    realcolname <- append(realcolname,as.character(temp.df[1,i]))
  }
  names(temp.df) <- realcolname
  ## strip 1st row
  final.df <- temp.df[2:nrow(temp.df),]
  return(final.df)
}

只需將 OpenOffice.Org Writer 文件的 codechunk 內容改少少:

#< -
table1 <-  doBy.t(summaryBy(Sepal.Length+Sepal.Width~Species, data=iris, FUN=meansd, keep.names=TRUE))

當然也要將 doBy.t() 的 code 也加進去。用 odfWeave 處理後出來的 table 就會很美麗了。


Powered by Jekyll and profdr theme