In: Statistics and Probability
Write a function in R named counts.
This function should take as parameters a numeric vector x and also a number indicating a number of bins n. The function will consider the range [min(x),max(x)], and then consider a parti- tion of this interval into n non-overlapping equally sized half open intervals: I1 = [min(x),b1),I2 = [b1,b − 2),...,In = (bn−1,max(x)].
Note that since the intervals are equally sized, the value of bi is constrained. The function will then return a vector of length n such that the i-th element of this vector is the number of coordinates of x that lie in the interval Ii. Provide the code for this function: It should be of the following form:
counts = function(...) {
...
return(...)
}
Thank you for your help.
Here we have fixed a width of a class by dividing the range with the number of bins.
Then the bins are formed as given in the problem.
The R-code for this problem is,
counts <- function(x,n){
width <- (max(x)-min(x))/n
b <- array(dim=1)
b[1] <- min(x)+width
for(i in 2:(n-1)){
b[i] <- b[i-1]+width
}
#lower class limit
lcl <- c(min(x),b)
#upper class limit
ucl <- c(b,max(x))
frequency <- rep(0,n)
for(i in 1:length(x)){
if(x[i]==max(x))
frequency[n]
<- frequency[n] +1
for(j in 1:n){
if(lcl[j]<=x[i] && ucl[j]>x[i])
frequency[j] <- frequency[j] + 1
}
}
return(frequency)
}
The above program returns only the vector of frequency for a class. If we want to change it such that the lower and upper class limits, then we have to change the return part of the function to,
return(data.frame(lcl,ucl,frequency))
An example x and n, with the function is shown below,
counts(seq(1:11),4)