将 table 转换为数据框 R
Transform table into dataframe R
假设我们有以下数据:
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,我们得到以下结果:
table(df$type)
> new old recent
6 2 4
我正在寻找一个函数,该函数接收此 table 数据并将其转换为数据框,而不考虑列数。
理想情况下,数据框应如下所示:
type count
new 6
old 2
recent 4
这样就可以了:
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
这里有一些选项
> 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
使用 dplyr
中的 count
library(dplyr)
count(df, type, name = 'count')
type count
1 new 6
2 old 2
3 recent 4
假设我们有以下数据:
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,我们得到以下结果:
table(df$type)
> new old recent
6 2 4
我正在寻找一个函数,该函数接收此 table 数据并将其转换为数据框,而不考虑列数。 理想情况下,数据框应如下所示:
type count
new 6
old 2
recent 4
这样就可以了:
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
这里有一些选项
> 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
使用 dplyr
count
library(dplyr)
count(df, type, name = 'count')
type count
1 new 6
2 old 2
3 recent 4