2009-12-03 96 views
1

採取例如以下ftable轉換的ftable到基質

height <- c(rep('short', 7), rep('tall', 3)) 
girth <- c(rep('narrow', 4), rep('wide', 6)) 
measurement <- rnorm(10) 
foo <- data.frame(height=height, girth=girth, measurement=measurement) 
ftable.result <- ftable(foo$height, foo$girth) 

我想上述ftable.result轉換成具有行名和列名的矩陣。有沒有這樣做的有效方式? as.matrix()不能正確工作,因爲它不會爲您附加行名稱和列名稱。

你可以做以下

ftable.matrix <- ftable.result 
class(ftable.matrix) <- 'matrix' 

rownames(ftable.matrix) <- unlist(attr(ftable.result, 'row.vars')) 
colnames(ftable.matrix) <- unlist(attr(ftable.result, 'col.vars')) 

然而,這似乎有點重手。有沒有更有效的方法來做到這一點?

回答

2

我發現2 solutions on R-Help

head(as.table(ftable.result), Inf) 

或者

t <- as.table(ftable.result) 
class(t) <- "matrix" 
+0

我不知道你可以以這種方式使用'as.table'。 – andrewj 2009-12-03 22:21:09

2

事實證明,@Shane原先公佈(但很快就刪除)什麼一個正確的答案與較新版本的R 。

某處一路上,as.matrix方法被添加爲ftable(我還沒有在我通讀的新聞檔案中發現它。

as.matrix方法ftable可以很好地處理「嵌套」頻率表(這是ftable創建的很好)。考慮以下幾點:

temp <- read.ftable(textConnection("breathless yes no 
coughed yes no 
age 
20-24 9 7 95 1841 
25-29 23 9 108 1654 
30-34 54 19 177 1863")) 

class(temp) 
# [1] "ftable" 

head(as.table(...), Inf)招不這樣ftables工作,因爲as.table將結果轉換成一個多維數組。

head(as.table(temp), Inf) 
# [1] 9 23 54 95 108 177 7 9 19 1841 1654 1863 

出於同樣的原因,第二個建議,也不起作用:

t <- as.table(temp) 
class(t) <- "matrix" 
# Error in class(t) <- "matrix" : 
# invalid to set the class to matrix unless the dimension attribute is of length 2 (was 3) 

然而,隨着更多新版本的R,簡單地使用as.matrix就可以了:

as.matrix(temp) 
#  breathless_coughed 
# age  yes_yes yes_no no_yes no_no 
# 20-24  9  7  95 1841 
# 25-29  23  9 108 1654 
# 30-34  54  19 177 1863 

class(.Last.value) 
# [1] "matrix" 

如果您更喜歡data.framematrix,從我的"mrdwabmisc" package on GitHub檢出table2df