I am trying to build a function that takes a numeric vector of homework scores (of length n), and an optional logical argument drop, to compute a single homework value. If drop = TRUE, the lowest HW score must be dropped. The function should also return the average of the homework scores—but are I am not using mean().
step 1---- create a function to remove NA
remove_missing <- function(x){a<-is.na(x)x[!a]}
step2 create a function to drop lowest score
drop_lowest <- function(x,na.rm=TRUE) {if(na.rm==TRUE){
x = remove_missing(x)}
minX <- x[1] ## set target to first element of `x`
for (i in 1:length(x)) { ## i take values 2, 3, ..., length(x)
if(x[i] < minX) ## do comparison with current target
minX <- x[i] ## if element i is smaller than target, update
target
}
return(x[x != minX])
}
step3 function to get average
get_average <- function(x,na.rm=TRUE) {
if(na.rm==TRUE){
x = remove_missing(x)}
total <- 0
for (n in 1:length(x)) {
total= total + x[n]
}
return(total/length(x))
}
put it all together
score_homework <- function(x,drop=TRUE)
{
if(drop==TRUE)
x = drop_lowest(x)
{get_average(x)}}
However I keep getting the error Error in score_homework() : argument "x" is missing, with no default
Aucun commentaire:
Enregistrer un commentaire