R Programming Please help me to understand and write the programming as the foll
ID: 3334842 • Letter: R
Question
R Programming
Please help me to understand and write the programming as the following requirement. Thanks!
Write a function that bins data. This is the kind of thing one does when making a histogram. We are given a data vector x, and a vector containing the boundary of the bins. This vector is called bins.
Function prototype is: bin.data <- function(x,bins)
Check that bins is strictly increasing. The bins are open on the left and closed on the right (except for the last bin). For example, if bins = c(2.5,5,7.8,9) you are to determine if an element of x falls into the bin (-Inf,2.5], the bin (2.5,5], the bin (5,7.8], the bin (7.8,9], or the bin (9,Inf). Here x is a numeric data vector, and we want to bin the data. If bins has length m, then we return a vector of length (m+1). We do not allow –Inf or Inf values in bins.
The purpose of the function is to return a count of how many elements of x fall into each bin. Using the bins vector as defined above, If x = c(8.3, -2, 2.3, 7.9, 2.5, 2.51, 8.5, -8.9, 9.2) we return the vector c(4,1,0,3,1). The explanation of the output vector is given below.
There are four values of i such that x[i] <= bins[1]
There is one value of i such that bins[1] < x[i] <= bins[2]
There are zero values of i such that bins[2] < x[i] <= bins[3]
There are three values of i such that bins[3] < x[i] <= bins[4]
There is one value of i such that bins[4] < x[i]
Explanation / Answer
Here is R code for bins data
f= function(x,bins){
l=rep()
l[1]=length(which(x<=bins[1]))
for(i in 2:(length(bins))){
l[i]=length(which(x<=bins[i]&x>bins[i-1]))
}
l[length(bins)+1]=length(which(x>bins[length(bins)]))
l
}
f(x,bins)
The above function is just checking how many of x lie in bins interval.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.