- Overview of R
- Input and evaluation
- Atomic classes of objects
- Data types
- Help documents
- Working directory
- Reading and looking at data
- Extracting subsets
- Vectorized operations
- Control structures
- Writing functions
August 15, 2017
R as a language and a free software
<- as the assignment operator.= is also eligible but I recommend <-. Here is my reason for that.# starts comments. Comments won’t be executed.
x <- 5 name <- "Yu-Zhen" # keying my name in # Nothing happens.
Incomplete expressions
x <- 5 # inputting the value of x x # auto-printing
[1] 5
print(x) # explicit printing
[1] 5
Character, numeric, integer, complex, and logical
"Yu-Zhen", letters, "Hello world!"pi, 123, Inf10L, 123L7 + 3iTRUE or FALSEclass to find out which class the object is.NA (Not Available) and NaN (Not a Number)NaN is an NA, but the converse is false.is.na and is.nan are used to test if objects are NA and NaN, respectively.Vector, list, matrix, factor, and data frame
c (or vector) to create a vector.m:n.Coercion occurs when different classes are input. (logical < integer < numeric < complex < character)
c(TRUE, 1 + 3i, "Yay!")
[1] "TRUE" "1+3i" "Yay!"
Explicit coercion can be performed with as.* functions.
list to create a list.Lists are similar with vectors but accept different classes of elements.
my_list <- list(1:3, letters, TRUE) my_list2 <- list(first = 1:3, second = letters, third = TRUE) # What's the difference between my_list and my_list2?
Create a list like this:
$one [1] "a" "b" "c" "d" $two [1] 76 77 78 79 80 $three [1] TRUE FALSE TRUE
Use matrix to create a matrix (column-wise by default).
matrix(1:6, 2, 3)
[,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6
Bind columns or rows by cbind or rbind respectively.
rbind(1:4, 5:8)
[,1] [,2] [,3] [,4] [1,] 1 2 3 4 [2,] 5 6 7 8
factor creates factors from vectors.The “levels” argument can be specified to assign base level.
factor(c("high", "high", "low", "mid", "low"),
levels = c("low", "mid", "high"))
[1] high high low mid low Levels: low mid high
Pay extra attention when coercing factors into numbers.
data.frame can create one data frame.cbind and rbind are also effective for data frames.Try to make the following data frame. Save the object as "practice.frame".
Hint: It's like creating a list but with the same length of vectors.
num age RT MMSEpass 1 1 young 12 TRUE 2 2 old 50 FALSE 3 3 young 15 TRUE
? or help gets the help document of the function.
?? or help.search finds functions with the key word.getwd retrieves current working directory path.setwd sets another specific path as working directory.Let’s create a folder and set it as the working directory for this tutorial! Download the following two files and put them in that directory.
Please avoid Chinese characters and spaces in your path.
read.table/write.table;load/save.image;source/dump
read.table or read.csv inputs a table into R as a data frame.file.choosedemo.table <- read.csv("r-tutorial-demo.csv")write.table or write.csv outputs data in a spreadsheet.load inputs previously saved workspace into R.save.image saves the whole current workspace as a .RData file.
save.image("tutorial.RData") # Save the whole workspace
q() # Quit the R session
# After turning on a new R session and setting the working directory
load("tutorial.RData")source inputs a written .R file into R.dump can be used to save .R files.demo.table
age sex height 1 young female 173.1 2 young male 167.5 3 young male 159.2 4 young male 148.1 5 old female 165.9 6 young female 157.7 7 young male 163.6 8 young male 164.4 9 old female 159.7 10 old female 160.3
head(demo.table)
age sex height 1 young female 173.1 2 young male 167.5 3 young male 159.2 4 young male 148.1 5 old female 165.9 6 young female 157.7
# Try tail(demo.table) by yourself
summary(demo.table)
age sex height
old :3 female:5 Min. :148.1
young:7 male :5 1st Qu.:159.3
Median :161.9
Mean :161.9
3rd Qu.:165.5
Max. :173.1
str(demo.table)
'data.frame': 10 obs. of 3 variables: $ age : Factor w/ 2 levels "old","young": 2 2 2 2 1 2 2 2 1 1 $ sex : Factor w/ 2 levels "female","male": 1 2 2 2 1 1 2 2 1 1 $ height: num 173 168 159 148 166 ...
Take a look at the data frame you created earlier.
'data.frame': 3 obs. of 4 variables: $ num : int 1 2 3 $ age : Factor w/ 2 levels "young","old": 1 2 1 $ RT : num 12 50 15 $ MMSEpass: logi TRUE FALSE TRUE
[] extracts elements by names, indexes, or logical values.
[[]] extracts elements from lists and data frames.
$ extracts elements by name.By default, subsetting a single row or a single column from a matrix will return a vector, unless the argument "drop" is FALSE.
demo.table$height
[1] 173.1 167.5 159.2 148.1 165.9 157.7 163.6 164.4 159.7 160.3
# What if I only need the 2nd, 4th, and 5th elements of the heights?
x <- 1:3 y <- 4:6 # x + y = ? a <- 1:4 b <- 1:2 # a - b = ? m <- matrix(6, 2, 2) n <- matrix(1:4, 2, 2) # m * n = ? # m %*% n = ?
if, for, while. These loops can be nested.
== (equal to)>= (greater than or equal to)<= (less than or equal to)> (greater than)< (less than)!= (not equal to)! (not)& (and)| (or)
1:3 != 2
[1] TRUE FALSE TRUE
if (<condition 1>) {
# do something
# the only necessary part of if structures
}
else if (<condition 2>) {
# do something different
}
else {
# do something else
}
A for loop takes an iteration variable, and assigns it successive values from a sequence or a vector.
x <- c(90, 87, 60, 45, 50)
for (i in 1:5) {
if (x[i] >= 60) {
print("Pass")
}
else {
print("Fail")
}
}
[1] "Pass" [1] "Pass" [1] "Pass" [1] "Fail" [1] "Fail"
while loops begin with testing a condition. If it is true, then execute the body. After the execution, the condition will be tested again.while loops can possibly cause infinite loops if not written properly.
i <- 1
while (i < 4) {
i <- i + 1
print(i)
}
[1] 2 [1] 3 [1] 4
practice.table$waist[10] <- 27.add <- function(x, y) {
x + y
}
add(2, 3)
[1] 5
Try to create a function, which can subset and print out elements greater than a specified number from a numeric vector.
greaters <- function(x, n) {
# Your codes here
}
# For example, greaters(1:5, 3) should return 4 and 5.