假設我們有以下資料:
user <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
type <- c('new', 'recent', 'recent', 'old', 'recent', 'new', 'new', 'old', 'new', 'new', 'new', 'recent')
df <- data.frame(user, type)
如果我們計算該表,我們會得到以下結果:
table(df$type)
> new old recent
6 2 4
我正在尋找一個函式,該函式接收該表資料并將其轉換為資料幀,而不管列數如何。理想情況下,資料框如下所示:
type count
new 6
old 2
recent 4
uj5u.com熱心網友回復:
這可以完成以下作業:
df2 <- as.data.frame(table(df$type))
> df2
Var1 Freq
1 new 6
2 old 2
3 recent 4
如果需要,您可以重命名 Var1 和 Freq:
colnames(df2) <- c("type", "count")
> df2
type count
1 new 6
2 old 2
3 recent 4
uj5u.com熱心網友回復:
這里有一些選項
> stack(table(df$type))
values ind
1 6 new
2 2 old
3 4 recent
> as.data.frame(table(df$type))
Var1 Freq
1 new 6
2 old 2
3 recent 4
uj5u.com熱心網友回復:
使用count來自dplyr
library(dplyr)
count(df, type, name = 'count')
type count
1 new 6
2 old 2
3 recent 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354154.html
上一篇:在R中創建一個三向列聯表
