Solution to the exercise
#Using a for cycle
factorial.1 <- function(x)
{
s = 1
for(i in 1:x)
s = s * (i)
return(s)
}
#Using a while cycle
factorial.2 <- function(x)
{
s = 1
i = 1
while(i <= x)
{ s = s*i
i = i+1}
return(s)
}
#Using a repeat function
factorial.3 <- function(x)
{
s = 1
i = 1
repeat
{
s = s * i
i = i + 1
if (i > x)
{return(s)
break}
}
}
#Using a wrapper function (this is cheating!)
factorial.4 <- function(x)
return(factorial(x))
#Finding the average height for trees whose diameter is above the median
detXDom <- function(Ht, DBH)
{
if(length(Ht) != length(DBH)) return("Error)
Ht <- Ht[order(DBH, decreasing = TRUE)]
DBH <- DBH[order(DBH, decreasing = TRUE)]
Ht2 <- subset(Ht, DBH > median(DBH))
return(mean(Ht2, na.rm = TRUE))
}