In: Computer Science
this code should be in R.
Write function(s) to drop the smallest one exm grade out of several Exm grades. If a student misses an exm, the grade is NA. You must use NA instead of 0 to represent the value for exms missing. (a) Develop a function to convert an array to another array in which all NA grades are replaced with zero. (b) Complete your function to compute the mean of all elements row by row after dropping exactly one lowest grade. You cannot use any loop statement inside or outside your functions for both (a) and (b). You may use the built-in function in R to find the minimum value in an array. You may use ifelse() only once. You may use the built-in function mean() to find the mean. But be careful! For testing purpose, you may use the following exm grades for each student in each row:
Exm 1 Exm 2 Exm 3 Exm 4
80 NA 90 NA
60 80 100 NA
90 80 100 40
The average grade of each student must be displayed as a row in a matrix. For the exmple above, you need to display a 3 x 1 matrix with three rows of mean values in one column.
You may use functions: is.na() or na.omit().
Below is the screenshot of code and output:
Below is the R code for same. As mentioned in the question loops have not been used. For part a, is.na() function is used and for part b, apply() function is used. The implemented functions are also tested against the example given in the question.
#implementing function for part a to replace NAs with 0
replace_NA <- function(data) {
data[is.na(data)] <- 0
return(data)
}
#helper function for part b to find avg of a row after dropping
minimum grade
mean_after_removing_min <- function(data) {
return((sum(data)-min(data))/(length(data)-1))
}
#implementing required function for part b to return an avg matrix
after removing minimum grade
average_grade_after_dropping_min <- function(data) {
return(matrix(apply(data,1,mean_after_removing_min),dimnames
=list(c(unlist(dimnames(result)[1])),c("Avg grade")) ))
}
#TESTING
column.names <- c("Exm 1","Exm 2","Exm 3","Exm 4")
row.names <- c("Student_1","Student_2","Student_3")
matrix.names <- c("Exam Grades for students")
result <- array(c(80,60,90,NA,80,80,90,100,100,NA,NA,40),dim =
c(3,4,1),dimnames =
list(row.names,column.names,matrix.names))
print(result)# printing test case example
print("Now replacing NA's with 0s")
result = replace_NA(result)#Now replacing NA's with 0s
print(result)#printing modified array
#printing matrix containing averages computed for each student
post dropping lowest grade
print(average_grade_after_dropping_min(result))