I was working on Binning by Mean, Median and Boundary in R.
# R CODE
a=c(20.5, 52.5, 62.6, 72.4, 104.8, 63.9, 35.3, 83.9, 37.4, 71.6, 74.6, 44.5, 66.6, 56.1, 45.3, 37.2)
a=sort(a)
binsize=4
median(a[1:4])
# BINS ARE
for(i in 1:length(a))
{
if(i%%binsize==0)
{
print("HI")
print(a[i-3])
print(a[i-2])
print(a[i-1])
print(a[i])
}
}
# BINNING BY MEAN
sum=0
for(i in 1:length(a))
{
sum=sum+a[i]
if(i%%binsize==0){
avg=sum/binsize
sum=0
print(rep.int(avg,binsize))
}
}
# BINNING BY MEDIAN
i=1
for(i in 1:length(a)){
if(i%%binsize==0)
{
print(rep.int(median(a[i-3:i]),binsize))
}
}
Can anyone tell me why binning by median is giving me wrong output.
The median(a[i-3:i])
for 1st bin returns a value which is not same as median(a[1:4])
for 1st bin. Why?
for(i in 1:length(a)){ if(i%%binsize==0) {...}}
, just useseq(...by)
argument:for(i in seq(binsize, length(a), by=binsize)) { ... }
$\endgroup$