#1
math <- function (x)
sin(x)^2+cos(x)^2
math(600)
## [1] 1
#2
#The advangtage of a while loop is that we can have an exit condition without knowing how many times it will need to be repeated. It also allows for many different stopping conditions as opposed to the for loop. While loops are also typically shorter
i <- 1
while (i <= 1) i <- i+4
i
## [1] 5
i <- 1
while (TRUE) {
i <- i+4
if (i > 10) break
}
i
## [1] 13
#3
u = matrix (c(4,3,2,1), nrow = 2)
u
## [,1] [,2]
## [1,] 4 2
## [2,] 3 1
v = matrix (c(3,4,5,6),nrow = 2)
v
## [,1] [,2]
## [1,] 3 5
## [2,] 4 6
#4
for (m in c("u","v")){
z <- get(m)
f <- lm(z[,2]~z[,1])
print(z)
return(summary(f))
}
## [,1] [,2]
## [1,] 4 2
## [2,] 3 1
#5
r <- 4
#r <- 15
if (r == 4){
x <- 1
}else{
x <- 3
y <- 4
}
x = 3
y <- if (x == 2) x else x +1
y
## [1] 4
x <- c(TRUE, FALSE, TRUE,FALSE)
y <- c(TRUE, TRUE ,FALSE,FALSE)
x & y
## [1] TRUE FALSE FALSE FALSE
x[1] && y[1]
## [1] TRUE
if (x [1]&& y[1]) print("both TRUE")
## [1] "both TRUE"
getwd()
## [1] "C:/Users/James/OneDrive/Desktop/R"
setwd("C:/Users/James/OneDrive/Desktop/R")
#read.excel(excelwork.xlxs)
oddcount <- function (x){
k <- 0
for (n in x){
if (n %%2 ==1)k <- k+1
}
return(k)
}
a = c(5,9,8,20,17)
oddcount(a)
## [1] 3
g <- function(x){
return (x +1)
}
g(1)
## [1] 2
f1 <- function(a,b) return(a+b)
f2 <- function(a,b)return(a+b)
f <- f1
f <- f2
f(3,2)
## [1] 5
g <- function(h,a,b)h(a,b)
g (f1,3,2)
## [1] 5
g(f2,3,2)
## [1] 5