data(mtcars)
mtcars = modify(mtcars,{
    var_lab(vs) = "Engine"
    val_lab(vs) = c("V-engine" = 0, 
                    "Straight engine" = 1) 
    var_lab(am) = "Transmission"
    val_lab(am) = c(automatic = 0, 
                    manual=1)
})
fre(mtcars$vs)
with(mtcars, cro(am, vs))
with(mtcars, cro_cpct(am, vs))
# multiple-choise variable
# brands - multiple response question
# Which brands do you use during last three months? 
set.seed(123)
brands = data.frame(t(replicate(20,sample(c(1:5,NA),4,replace = FALSE))))
# score - evaluation of tested product
score = sample(-1:1,20,replace = TRUE)
var_lab(brands) = "Used brands"
val_lab(brands) = make_labels("
                              1 Brand A
                              2 Brand B
                              3 Brand C
                              4 Brand D
                              5 Brand E
                              ")
var_lab(score) = "Evaluation of tested brand"
val_lab(score) = make_labels("
                             -1 Dislike it
                             0 So-so
                             1 Like it    
                             ")
fre(brands)
cro(brands, score)
cro_cpct(brands, score)
# 'cro_mean'
data(iris)
cro_mean(iris[, -5], iris$Species)
# 'cro_fun'
data(mtcars)
mtcars = modify(mtcars,{
    var_lab(vs) = "Engine"
    val_lab(vs) = c("V-engine" = 0, 
                    "Straight engine" = 1) 
    var_lab(hp) = "Gross horsepower"
    var_lab(mpg) = "Miles/(US) gallon"
})
# Label for 'disp' forgotten intentionally
with(mtcars, cro_fun(data.frame(hp, mpg, disp), vs, summary))
# or, the same with transposed summary
with(mtcars, cro_fun(data.frame(hp, mpg, disp), vs, function(x) t(summary(x))))
# very artificial example
a = c(1,1,1, 1, 1)
b = c(0, 1, 2, 2, NA)
weight = c(0, 0, 1, 1, 1)
cro_fun(b, a, weight = weight, 
     fun = function(x, weight, na.rm){
                 weighted.mean(x, w = weight, na.rm = na.rm)
             }, 
     na.rm = TRUE)
# comparison 'cro_fun' and 'cro_fun_df'
data(iris)
cro_fun(iris[, -5], iris$Species, fun = mean)
# same result
cro_fun_df(iris[, -5], iris$Species, fun = colMeans)  
# usage for 'cro_fun_df' which is not possible for 'cro_fun'
# calculate correlations of variables with Sepal.Length inside each group
cro_fun_df(iris[,-5], iris$Species, fun = function(x) cor(x)[,1])
# or, pairwise correlations inside groups
cro_fun_df(iris[,-5], iris$Species, fun = cor)
Run the code above in your browser using DataLab