Learners of R
(very much including myself), fall prey to making things more complicated than they need to be. So let's start with what we have, and what we want and let that lead us to the right question.
What we have is two real numbers -- 10.2 and 20.8. But, of course, it doesn't have to be those specific numbers. This a good time to bring up the essence of using R
f(x) = y
Yes, just like school algebra -- functions.
Unlike school algebra, in R
, x is an object, which can be as simple as a single integer or very complicated, indeed. What object should we start with here?
We know that the objects that this thread started with are two real numbers, but where did they come from?
Here's a vector with similar values
v <- seq(10,20,by = 0.1)
head(v)
#> [1] 10.0 10.1 10.2 10.3 10.4 10.5
Created on 2020-02-16 by the reprex package (v0.3.0)
Let's create a function
to extract another object, with the min
and max
values
v <- seq(10,20,by = 0.1)
find_min_max <- function(x) {c(min(v),max(v))}
find_min_max(v)
#> [1] 10 20
Created on 2020-02-16 by the reprex package (v0.3.0)
We can trim v
to make it look more like your original object
v <- seq(10,20,by = 0.1)
find_min_max <- function(x) {c(min(v),max(v))}
v <- v[2:(length(v)-1)]
my_vec <- find_min_max(v)
my_vec
#> [1] 10.1 19.9
Created on 2020-02-16 by the reprex package (v0.3.0)
Now, we have an object my_vec
with two real numbers (that are not integers), and it doesn't matter what real numbers you started with. Notice that in f(x) = y, we've given as an argument x = v and got back y or , my\_vec.
What should we do with our bright, shiny new object?
First, we want to find the set of all integers, i, such that min(my\_vec) < i < max(my\_vec).
Then, we want to see the set of all integers, i, such that min(my\_vec) <= i <= max(my\_vec).
Let's walk through the first, and leave the second as an exercise to the reader
(I just loved seeing that when I was a student!)
Recall that we have an object, my_vec
with two real numbers. In their object of origin, v
, there were a number of real numbers between the min
and max
, but not all of them were integers. So, how to we find those that were?
Or do we care?
No, we can make 11.1
into 11
, using floor()
as @joels suggested.
This was the motivation behind my suggestion to create a vector using round(x),1)
. We have two choices: starting with my_vector
we can fill in the integers or, starting with v
, we can convert to integers, using floor()
.
If we use floor
, we come up with multiple identical integers. But, we have unique()
that we can use to collapse them.
v <- seq(10,20,by = 0.1)
unique(floor(v))
#> [1] 10 11 12 13 14 15 16 17 18 19 20
Created on 2020-02-16 by the reprex package (v0.3.0)
Now, the only question to be answered for your problem is
Does this solve the first problem or the second problem?