Helpful Code#
The very basics of R code are demonstrated below:
Importing data from a URL
Calculating and Displaying the Standard Descriptives and the 5-Number Summary
Using the cat() function to print text and code output together with some formatting options.
We also include helpful commands, for example, the code that creates functions for
Permutations
Combinations
Importing Data from a URL#
Many data sets are available on the internet in CSV format. The read.csv() function is very useful:
A URL is its input.
From the URL, R downloads the CSV file.
From the CSV, R imports the file as a data frame.
A typical example is shown below along with extracting the column Sleep as the data vector s:
pers <- read.csv('https://faculty.ung.edu/rsinn/data/personality.csv')
head(pers,3)
s <- pers$Sleep
Age | Yr | Sex | G21 | Corps | Res | Greek | VarsAth | Honor | GPA | ... | Perf | OCD | Play | Extro | Narc | HSAF | HSSE | HSAG | HSSD | PHS |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21 | 2 | M | Y | Y | 1 | N | N | N | 3.23 | ... | 105 | 10 | 142 | 8 | 11 | 41 | 40 | 26 | 27 | SE |
20 | 3 | F | N | N | 2 | Y | N | Y | 3.95 | ... | 105 | 3 | 172 | 16 | 11 | 46 | 52 | 26 | 33 | SE |
22 | 3 | M | Y | N | 2 | N | N | N | 3.06 | ... | 73 | 1 | 134 | 15 | 11 | 48 | 42 | 44 | 29 | AG |
Standard Descriptives and cat()#
We offer the following code from the Descriptive Statistics section. This bit is quite helpful in many cases, especially during explartory data analsyis.
cat('The standard descriptives for SLEEP\n Mean = ', round(mean(s),2),
'\n Standard Deviation = ', round(sd(s),2),
'\n Sample Size = ', length(s),
'\n\nThe 5-number summary for SLEEEP')
summary(s)
The standard descriptives for SLEEP
Mean = 6.24
Standard Deviation = 2.13
Sample Size = 129
The 5-number summary for SLEEEP
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.50 5.00 6.50 6.24 7.50 11.00
Combination and Permutations#
In probability problem-solving, we often need to evaluate combinations and permutations in R. Below is the code we use to create these functions.
combin <- function(n, k) {
return(factorial(n) / ( factorial(k)*factorial(n-k) )) }
perm <- function(n, k) {
return(combin(n,k) * factorial(k))}