Back to main workshop page

Sorry, this is going to be a bit rough. All of the code is below but I won’t have time to annotate it before the lecture. Please check back later!


# Let's write a function called isPrime() that checks if a number is prime.
# It will print one of the following: 
### Invalid input: (single number or integer)
### The number xx is not a prime because it is not greater than 1.
### The number xx is not a prime, its smallest divisor is yyy.
### The number xx is a prime.

isPrime(87)

3/2
3+2
3 %% 2

isPrime <- function(num){
  # It will print one of the following:
  ### Invalid input (input is not a single number, input is not an integer)
  ### The number xx is not a prime because it is not greater than 1.
  ### The number xx is not a prime, its smallest divisor is yyy.
  ### The number xx is a prime.
  if(length(num) != 1){
    return('Invalid Input')
  }
  if(num %% 1 !=0){
    return('Invalid Input')
  }
  if (num <=1){
    output <- paste('The number ', num, 'is not a prime because it is not greater than 1')
    return(output)
  }
  count <- 2
  while(count < num/2){
    # check if num divides into count.
    if( (num/count)%%1 ==0){
      output <- paste('The number ', num, 'is not a prime, its smallest divisor is', count)
      return(output)
    }
    count = count + 1
    # if it does, it's not a prime, return the right output
    # if num doesn't divide into count, add 1 to count and try again.
  }
  output <- paste('The number', num, 'is prime.')
  return(output)
}
isPrime(2)
isPrime(3)
isPrime(4)
isPrime(-100)

### What if we want to check a bunch of numbers?
# This function can only check one number at a time:
# e.g. isPrime(1,2,3) doesn't work...
values <- 1:100

# use sapply to go through all of our numbers and find out if they're prime
# first input is the values
# the second one is the function
sapply(values, isPrime )

for(a in values){
  print(a)
}

for (animals in c('bat', 'cat', 'dog')){

  b <- toupper(animals)
  print(animals)
  print(b)
  }



# What if we want biggest primes?

# 2^n -1
2^1 -1
2^2-1
2^3 -1
2^4 -1
# instead of checking 1,2,3,4,5...
# let's only check 2^1-1, 2^2 -1 2^3 -1

values <- 1:100

for (i in values){

  print(isPrime(i))
}


count = 2

while (count <= 100){
  print(count)
  count = count +1
  if (count ==50){
    break
  }
}

count = 2
repeat{
  print(count)
  if (count > 100){
    break
  }else{
    count = count+1
  }
}





data(iris)
head(iris)
sp <- unique(iris$Species)
i = 'setosa'
for (i  in sp){
  print(i)
  dat_i <- iris[iris$Species == i,]

  plot(Sepal.Length ~ Sepal.Width, data = dat_i, main = i)

}


iris$Species == i
iris[1,1]
iris[3,1]