Fun with R

Variables and Numbers

x<- 1
y = 2
3 -> z
x+y
## [1] 3
x*z
## [1] 3
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,4)
## [1] 0 1 2 3
tail(b,5)
## [1]  0 -1 -2 -3 -4

Combine Operator for creating vectors

when we create a vector with multiple data types, R coerces the vector to the most 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.5)
print(d)
## [1]  1.0  2.0  3.0  4.0  5.0 10.5
class(d)
## [1] "numeric"
str(d)
##  num [1:6] 1 2 3 4 5 10.5

Sequence Operator Application

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

Dropping Missing Values and Summarizing values

a <- c(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
a <-c(2,3,-1,3,5,2,-3,1)

print(paste0("The sum of positive integers in a=" ,sum(a[a > 0])))
## [1] "The sum of positive integers in a=16"
cat("The sum of positive integers in a=" ,sum(a[a > 0]))
## The sum of positive integers in a= 16

Creating the 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
M2 <- matrix(1:12, nrow = 4)
M2 
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12

##Accessing Matrix Element

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

Creating the Data Frame

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