# When it comes to undertaking complex data science projects, 
# R is the preferred choice for many. Why? Because handling complex tasks is
# impler in R than other comparable platforms.

# Regrettably, the same is not true for performing simpler tasks, 
# which I would argue is rather complex in base R. Hence, the title - 
 
# R: simple for complex tasks, complex for simple tasks.

# You can read the article at:

# https://medium.com/@regionomics/r-simple-for-complex-tasks-complex-for-simple-tasks-2a72eec628fb

data(mtcars)
head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
mean.cars <- with(mtcars, sapply(mtcars[c("mpg", "disp",  "hp")], mean)); mean.cars
##       mpg      disp        hp 
##  20.09062 230.72188 146.68750
sd.cars <- with(mtcars, sapply(mtcars[c("mpg", "disp",  "hp")], sd)); sd.cars
##        mpg       disp         hp 
##   6.026948 123.938694  68.562868
n.cars <- with(mtcars, sapply(mtcars[c("mpg", "disp",  "hp")], length)); n.cars
##  mpg disp   hp 
##   32   32   32
cbind(n.cars, mean.cars, sd.cars)
##      n.cars mean.cars    sd.cars
## mpg      32  20.09062   6.026948
## disp     32 230.72188 123.938694
## hp       32 146.68750  68.562868
round(cbind(n.cars, mean.cars, sd.cars),2)
##      n.cars mean.cars sd.cars
## mpg      32     20.09    6.03
## disp     32    230.72  123.94
## hp       32    146.69   68.56
round(with(mtcars, t(sapply(mtcars[c("mpg", "disp",  "hp")], 
                    function(x) c(n=length(x), avg=mean(x), stdev=sd(x))
                    ))), 2)
##       n    avg  stdev
## mpg  32  20.09   6.03
## disp 32 230.72 123.94
## hp   32 146.69  68.56
attach(mtcars)
library(stargazer)
## 
## Please cite as:
##  Hlavac, Marek (2015). stargazer: Well-Formatted Regression and Summary Statistics Tables.
##  R package version 5.2. http://CRAN.R-project.org/package=stargazer
stargazer(mtcars[c("mpg", "disp",  "hp")], type="text")
## 
## ============================================
## Statistic N   Mean   St. Dev.  Min     Max  
## --------------------------------------------
## mpg       32 20.091   6.027   10.400 33.900 
## disp      32 230.722 123.939  71.100 472.000
## hp        32 146.688  68.563    52     335  
## --------------------------------------------