2017-11-05 21_03_42-Lists _ StackSkills.png

Understanding the lists – a nice visualization

Copy and paste the following code to your R Studio platform or R version:

# ——————– R Essentials ——————————–#
# Lists
set.seed(100)
x <- letters # is a constant built-in function in R
x

y <- 1:26
y

z <- round(runif(26, 1, 26))
z

# Having the 3 variables in the same object and preserving their type
m <- list(x,y,z)
m
class(m)

m[1]
class(m[1])
class(m[[1]])
m[[1]][4]

# Or
m1 <- unlist(m)
m1

m1[4]
# however, now the numbers are also characters

# Let’s go a level deeper
n <- list(x,m)
n
# Getting the letter d now, seems a bit challenging
n[[2]][[1]][4]

# where is the letter r present?
m
m[[1]]
m[[2]]
m[[2]][m[[1]] == “r”]

# Set operations
x <- c(1:7)
y <- c(4:10)

y[x]
x[y]

out <- x %in% y
out

# These are the numbers present in y
x[out]

a <- c(x,y)
a
length(a)
# we have some duplicates in the a vector
length(unique(a))

# we could have combined the two by other ways
union(x,y)
intersect(x,y)

# Remove all items from y that are present in x
x
y
setdiff(y,x)

# ——————————————————– #
# Find the items that are not common between these two (x,y)
x
y
setdiff(union(x,y), intersect(x,y))

# Sampling and Sorting
a <- 1:100
a

# Let’s pick 10 random numbers as a sample from the a
set.seed(100)
# set the seed so the results are reproducible
sample(a, 10)

# What if we want to allow replacements?
b <- sample(a, 30, replace = TRUE)
b

sort(b)
sort(b, decreasing = TRUE)

b
o <- order(b) #it gives the position of the original items in the increasing order
b[o]

# or
rev(b[o])
# which is the same as
b[order(-b)]

# Check conditions
a <- 2
b <- 5

if(a < b) {

print(“Less”)

} else {

print(“More”)

}

a <- 1:10
ifelse(a%%2 == 0, “Even”, “Odd”)
ifelse(sum(a) < 5, x <- “The sum is less than 5”, x <- “The sum is more than 5”)
x

# Challenge: Create a character vector of same length as a that has yes in positions
# where the number is a multiple of three and no otherwise

a <- round(runif(15, 1, 100))
char <- ifelse(a%%3 == 0, “Yes”, “No”)
char

# For Loops
for(i in 1:10){

print(i)

}

# Skip a loop
for(i in 1:10){
if(i == 5){
next
}

print(i)

}

# Break out of the loop
for(i in 1:10){
if(i == 5){
break
}

print(i)

}

Posted by Dimitris

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s