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

x <- c(1, 13, 23, 50)
y <- seq(0, 10, 2)
z <- rep(“Hi there!”, 3)

x
y
z

# accessing individual elements of a vector
w <- c(“a”, “b”, “c”, “d”, “e”)
w
w[1]
w[1:3]
w[-1]
w[3:5]
w[c(1, 3, 5)]
w[c(-2, -4)]

v <- w[1:2]
v

# Vectorized operations

x <-rnorm(5)
x

# R-specific programming loop

for(i in x) {

print(i)

}

# The same as the following:

print(x[1])
print(x[2])
print(x[3])
print(x[4])
print(x[5])

# Or, the conventional programming loop:

for(j in 1:5){

print(x[j])

}

# Compare vvectorized and de-vectorized operations

N <- 100
a <- rnorm(N)
b <- rnorm(N)

# Vectorized approach-in R this type is faster

c <- a * b

# De-vectorized approach-as N gets larger the executions time explodes
# Try both apporaches with N = 10000, N = 100000 and N = 10000000

d <- rep(NA, N)
for(i in 1:N) {

d[i] <- a[i] * b[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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s