Box the compass: Difference between revisions

Added R (Arrrr!) version
(Box the compass in True BASIC)
(Added R (Arrrr!) version)
Line 5,920:
compasspoint$ = point$(INT(x))
END FUNCTION</lang>
 
 
=={{header|R}}==
 
R (also known as Arrr me hearties!) is ideally suited to this task. Here's an easy to understand but inefficient way to solve it:
 
<lang R>
pts <- data.frame(
des = c("N", "NxE", "NNE", "NExN", "NE", "NExE", "ENE", "ExN",
"E", "ExS", "ESE", "SExE", "SE", "SExS", "SSE", "SxE",
"S", "SxW", "SSW", "SWxS", "SW", "SWxW", "WSW", "WxS",
"W", "WxN", "WNW", "NWxW", "NW", "NWxN", "NNW", "NxW",
"N")
)
pts$deg <- seq(0, 360, 360/32)
 
heading <- Vectorize(function(deg) {
res <- pts
res$diff <- abs(res$deg - deg)
res <- res[order(res$diff), ]
res[1,]$des[1]
})
</lang>
 
Here are the test inputs:
 
<lang R>
test <- data.frame(
deg = c( 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37,
84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75,
185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13,
270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37,
354.38)
)
 
test$heading <- heading(test$deg)
test
</lang>
 
Check that the output headings cover the full range of headings:
 
<lang R>
all.equal(test$heading, pts$des)
</lang>
 
{{out}}
<pre>
> test
deg heading
1 0.00 N
2 16.87 NxE
3 16.88 NNE
4 33.75 NExN
5 50.62 NE
6 50.63 NExE
7 67.50 ENE
8 84.37 ExN
9 84.38 E
10 101.25 ExS
11 118.12 ESE
12 118.13 SExE
13 135.00 SE
14 151.87 SExS
15 151.88 SSE
16 168.75 SxE
17 185.62 S
18 185.63 SxW
19 202.50 SSW
20 219.37 SWxS
21 219.38 SW
22 236.25 SWxW
23 253.12 WSW
24 253.13 WxS
25 270.00 W
26 286.87 WxN
27 286.88 WNW
28 303.75 NWxW
29 320.62 NW
30 320.63 NWxN
31 337.50 NNW
32 354.37 NxW
33 354.38 N
 
> all.equal(test$heading, pts$des)
[1] TRUE
</pre>