Bin given limits: Difference between revisions
m
→{{header|R}}: Improved syntax.
ReeceGoding (talk | contribs) m (→{{header|R}}: Syntax highlighting.) |
ReeceGoding (talk | contribs) m (→{{header|R}}: Improved syntax.) |
||
Line 1,945:
Code such as 0:length(limits) is generally considered bad practice, but it didn't cause any problems here. To my amazement, this code works even if limits is of size 0 or 1. Even the <= printing doesn't break!
<lang rsplus>limits1 <- c(23, 37, 43, 53, 67, 83)
data1 <- c(95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16,8,9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55)
limits2 <- c(14, 18, 249, 312, 389, 392, 513, 591, 634, 720)
data2 <- c(445,814,519,697,700,130,255,889,481,122,932,
416,589,930,373,202,253,775,
655,267,248,477,549,238,
346,860,
345,110,720,917,313,845,426,
854,740,
787,942,456,242,759,898,576,
698,765,331,487,251,600,879,342,982,527,736,795,585,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466,
createBin <- function(limits, data)
{
sapply(0:length(limits), function(x) sum(findInterval(data, limits) == x))
}
Line 1,968:
#Half of the battle here is making sure that we're not being thrown by R being 1-indexed.
#The other half is avoiding the mathematical sin of saying that anything can be >=infinity.
printBin <- function(limits, bin)
{
invisible(sapply(0:length(limits), function(x) cat("Bin", x, "covers the range:",
if(x == 0)
if(x == length(limits))
"and contains", bin[x + 1], "elements.\n")))
}
#Showing off a one-line solution. Admittedly, calling the massive anonymous function "one-line" is generous.
oneLine <- function(limits, data)
{
invisible(sapply(0:length(limits), function(x) cat("Bin", x, "covers the range:",
if(x == 0)
if(x == length(limits))
"and contains", sum(findInterval(data, limits) == x),
"elements.\n")))
}
createBin(limits1, data1)
printBin(limits1, createBin(limits1, data1))
createBin(limits2, data2)
printBin(limits2, createBin(limits2, data2))
oneLine(limits2, c(data1, data2))#Not needed.</lang>
{{out}}
<pre>> createBin(limits1, data1)
[1] 11 4 2 6 9 5 13
> printBin(limits1, createBin(limits1, data1))
Bin 0 covers the range: -∞ < x < 23 and contains 11 elements.
Bin 1 covers the range: 23 ≤ x < 37 and contains 4 elements.
Line 2,004:
Bin 6 covers the range: 83 ≤ x < ∞ and contains 13 elements.
> createBin(limits2, data2)
[1] 3 0 44 10 16 2 28 16 6 16 59
> printBin(limits2, createBin(limits2, data2))
Bin 0 covers the range: -∞ < x < 14 and contains 3 elements.
Bin 1 covers the range: 14 ≤ x < 18 and contains 0 elements.
Line 2,020:
Bin 10 covers the range: 720 ≤ x < ∞ and contains 59 elements.
> oneLine(limits2, c(data1, data2))#Not needed.
Bin 0 covers the range: -∞ < x < 14 and contains 10 elements.
Bin 1 covers the range: 14 ≤ x < 18 and contains 2 elements.
|