3 min read

Fun with R

Variables and Numbers

x <- 1
y = 2
3 -> z
x + y
## [1] 3
y*z
## [1] 6
y/x
## [1] 2

Vectors

a <- 0:10
print(a)
##  [1]  0  1  2  3  4  5  6  7  8  9 10
b <- 10:-4
print(b)
##  [1] 10  9  8  7  6  5  4  3  2  1  0 -1 -2 -3 -4
class(a)
## [1] "integer"
str(a)
##  int [1:11] 0 1 2 3 4 5 6 7 8 9 ...
a[c(1, 5, 10)]
## [1] 0 4 9
head(a)
## [1] 0 1 2 3 4 5
head(a, 4)
## [1] 0 1 2 3
tail(b, 5)
## [1]  0 -1 -2 -3 -4

Combine operator for creating vector

When we creat a vector with multiple data types, R coerces the vector to the most compatible data type

c <- c(1:5, 10.5, 'red', 'yellow', 'green')
print(c)
## [1] "1"      "2"      "3"      "4"      "5"      "10.5"   "red"    "yellow"
## [9] "green"
class(c)
## [1] "character"
str(c)
##  chr [1:9] "1" "2" "3" "4" "5" "10.5" "red" "yellow" "green"
d <- c(1:5, 10)
print(d)
## [1]  1  2  3  4  5 10
class(d)
## [1] "numeric"
str(d)
##  num [1:6] 1 2 3 4 5 10

Sequense operator application

x <- seq(0, 8*pi, length.out = 200)
y <- sin(x)
plot(x, y)

## Dropping missing values

a <- c(3,-2,4,NA,-1,8,-4,9,NA, 11,3,8,NA)
a
##  [1]  3 -2  4 NA -1  8 -4  9 NA 11  3  8 NA
a[!is.na(a)]
##  [1]  3 -2  4 -1  8 -4  9 11  3  8

Dropping missing values and summarizing values

a <- c(2,3,-1,3,5,2,-3,1)
sum(a[a>0])
## [1] 16
print(paste0("The sum of positive integers in a", sum(a[a>0])))
## [1] "The sum of positive integers in a16"
cat("The sum of positive integers in a", sum(a[a>0]))
## The sum of positive integers in a 16

Matrix

M1 <- matrix(1:12, ncol = 4, byrow = TRUE)
M1
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
M1[2, 2]
## [1] 6
M1[2,]
## [1] 5 6 7 8
M1[,2]
## [1]  2  6 10
M2 <- matrix(1:12, nrow = 4)

Accessing Matrix Elements

M1 <- matrix(1:20, ncol = 4)
M1[c(3,5), c(2,4)]
##      [,1] [,2]
## [1,]    8   18
## [2,]   10   20

Data Frames

DF <- data.frame(
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
age =c(42,38,26),
row.names=c('Ally','Belinda','Alfred')
)
DF
##         gender height weight age
## Ally      Male  152.0     81  42
## Belinda   Male  171.5     93  38
## Alfred  Female  165.0     78  26
DF$age
## [1] 42 38 26
DF[DF$gender == "Male",]
##         gender height weight age
## Ally      Male  152.0     81  42
## Belinda   Male  171.5     93  38