【发布时间】:2015-09-19 15:08:34
【问题描述】:
我想根据不同的组合计算分类变量的频率和相对频率。我已经计算了频率,但没有成功地将输出传输到相对频率计算。有人可以帮我找出错误吗?
# Random generation of values for categorical data
set.seed(33)
df <- data.frame(cat1 = sample( LETTERS[1:2], 100, replace=TRUE ),
cat2 = sample( LETTERS[3:5], 100, replace=TRUE ),
cat3 = sample( LETTERS[2:4], 100, replace=TRUE ),
var1 = sample( LETTERS[1:3], 100, replace=TRUE ),
var2 = sample( LETTERS[3:8], 100, replace=TRUE ),
var3 = sample( LETTERS[2:3], 100, replace=TRUE ),
vre1 = sample( LETTERS[2:7], 100, replace=TRUE ),
vre2 = sample( LETTERS[1:5], 100, replace=TRUE ),
ref3 = sample( LETTERS[2:9], 100, replace=TRUE ),
con1 = runif(100,0,100),
con2 = runif(100,23,45))
# Calculating the frequency
library(dplyr)
cat.names <- c('var1','var3','vre2','ref3')
df %>% group_by(cat1, cat3) %>% summarise_each(funs(n = n()), one_of(cat.names))
# Piping it to calculate the relative frequency/Percentage
df %>% group_by(cat1, cat3) %>% summarise_each(funs(n = n()), one_of(cat.names)) %>% mutate(freq = n / sum(n))
# Error
Error: invalid 'type' (closure) of argument
#Expected Output
cat1 cat3 var1.freq var3.freq vre2.freq ref3.freq var1.rfreq var3.rfreq vre2.rfreq ref3.rfreq
1 A B 8 8 8 8 0,153846154 0,153846154 0,153846154 0,153846154
2 A C 27 27 27 27 0,519230769 0,519230769 0,519230769 0,519230769
3 A D 17 17 17 17 0,326923077 0,326923077 0,326923077 0,326923077
4 B B 16 16 16 16 0,333333333 0,333333333 0,333333333 0,333333333
5 B C 12 12 12 12 0,25 0,25 0,25 0,25
6 B D 20 20 20 20 0,416666667 0,416666667 0,416666667 0,416666667
【问题讨论】:
-
这里的列名仍然是 var1 var3 vre2 ref3。查看
df %>% group_by(cat1, cat3) %>% summarise_each(funs(n = n()), one_of(cat.names))的输出通过调用mutate(freq=n/sum(n)),你的目标是哪一列? -
@akrun 是的,我可以观察到这一点。我也尝试将
cat.names中的每个变量传递给mutate,但没有成功。 -
也许
df %>% group_by(cat1, cat3) %>% summarise_each(funs(n()/nrow(df)), one_of(cat.names))有预期的输出会更好 -
您是否在寻找每个组中独特元素的频率?在这种情况下,
n_distinct可能有用。即df %>% group_by(cat1, cat3) %>% summarise_each(funs(n_distinct(.)/n()), one_of(cat.names)) -
@akrun 不,我正在寻找每个组的元素频率及其百分比份额。