我有以下数据集:
set.seed(6)
df <- data.frame(a=floor(runif(100)*5),b=floor(runif(100)*4),c=floor(runif(100)*3))
Run Code Online (Sandbox Code Playgroud)
我想为每个变量生成汇总freq表并将它们存储在一个数据集中.例如.
outexample <- rbind(table(df$a),c(table(df$b),0),c(table(df$c),0,0))
rownames(outexample) <- letters[1:3]
outexample
0 1 2 3 4
a 19 18 20 18 25
b 30 23 19 28 0
c 28 33 39 0 0
Run Code Online (Sandbox Code Playgroud)
每个变量中有数百个变量和未知数量的类.有没有更好的方式来做到这一点?
您可以使用stack()和table()- 并t()获得所需的输出.
t(table(stack(df)))
# values
#ind 0 1 2 3 4
# a 19 18 20 18 25
# b 30 23 19 28 0
# c 28 33 39 0 0
Run Code Online (Sandbox Code Playgroud)
和data.table你一起做
library(data.table)
setDT(df)
dcast(data = melt(df), variable ~ value)
Run Code Online (Sandbox Code Playgroud)