Below is a data frame of students and how they scored on two quizzes.
Student <- c("Aaron","Baron","Caron","Daron","Earon","Faron","Garon","Haron","Iaron","Jaron")
Quiz1 <- c(15, 17, 19, 13, 7, 20, 5, 17, 16, 15.5)
Quiz2 <- c(12, 19, 4, 11, 11, 7.5, 20, 0, 8, 11)
DF <-data.frame(Student, Quiz1, Quiz2)
DF #Show the Date Frame
## Student Quiz1 Quiz2
## 1 Aaron 15.0 12.0
## 2 Baron 17.0 19.0
## 3 Caron 19.0 4.0
## 4 Daron 13.0 11.0
## 5 Earon 7.0 11.0
## 6 Faron 20.0 7.5
## 7 Garon 5.0 20.0
## 8 Haron 17.0 0.0
## 9 Iaron 16.0 8.0
## 10 Jaron 15.5 11.0
The mean of Quiz 1 and Quiz 2 is also reported below.
apply(DF[,c(2,3)], 2, mean) #mean of each quiz
## Quiz1 Quiz2
## 14.45 10.35
Another way to display/find the means.
#Another way not using apply()
mean(DF$Quiz1) #mean of Quiz 1
## [1] 14.45
mean(DF$Quiz2) #mean of Quiz 2
## [1] 10.35
Below is a function that prints the first n consecutive terms of f(x)=x^2-3x+20
f(10) is displayed.
f <- function(x){
for(i in 1:x){
cat(i^2-3*i+20, " ")
}
}
f(10)
## 18 18 20 24 30 38 48 60 74 90
Another way to display the numbers. f(5) is displayed.
f = function(x){
for (i in 1:x){
print(i^2-3*i+20)
}
}
f(5)
## [1] 18
## [1] 18
## [1] 20
## [1] 24
## [1] 30
Another way to display the numbers. f(7) is displayed.
f <- function(x){
print(x^2-3*x+20)
}
f(1:7)
## [1] 18 18 20 24 30 38 48