r - error in calculation of relative frequency of groups based on different combinations -
i calculate frequency , relative frequency of categorical variables based on different combinations. have calculated frequency , not successful in piping output relative frequency calculation. me in identifying error ?
# random generation of values 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 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 calculate 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 b 8 8 8 8 0,153846154 0,153846154 0,153846154 0,153846154 2 c 27 27 27 27 0,519230769 0,519230769 0,519230769 0,519230769 3 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
try
df1 <- df %>% group_by(cat1, cat3) %>% summarise_each(funs(n()), one_of(cat.names)) df2 <- df1 %>% group_by(cat1) %>% mutate_each(funs(./sum(.)), var1:ref3) bind_cols(df1, df2[-(1:2)])
Comments
Post a Comment