I think this should be easy to do. I have a data frame df
with several columns. In column a
I have different values between 1 and 100.
By comparing them I want to create a column new
in the df
to group them. The function to group them should round the value in a
to the nearest even integer and save it in df$new
. If a = 0
it should set new
to NA
.
See the following example:
... a ... new
---------------
0 NA
87.3 88
88.1 88
81.7 82
79.2 80
89.4 90
EVEN function in Excel returns the next even integer after rounding a given number up. Please note that EVEN function always rounds numbers up (away from zero) Number is a numeric value that you want to round up to the nearest Even integer For Row number 3 the nearest rounded up even integer will be 2 (moving away from zero)
If the integer part is EVEN, round towards zero. If the integer part of the number is ODD, round away from zero. In either case, the rounded number is an even integer. All rounding functions are discontinuous step functions that map the real numbers onto the integers.
Round the number 863178137 to the nearest multiple of 100. Round the elements of a vector to retain 2 significant digits. The format command controls how MATLAB® displays numbers at the command line. If a number has extra digits that cannot be displayed in the current format, then MATLAB automatically rounds the number for display purposes.
Specify 'significant' to round to N significant digits (counted from the leftmost digit). In this case, N must be a positive integer. Y = round(t) rounds each element of the duration array t to the nearest number of seconds. Y = round(t,unit) rounds each element of t to the nearest number of the specified unit of time.
I would suggest to use the internal round
function combined with division/multiplication with 2.
df <- data.frame(a = c(0, 87.3, 88.1, 81.7, 79.2, 89.4))
# Round to nearest even integer
df$new <- 2 * round(df$a/2)
# Set 0 values of original array to NA in the result
df$new[df$a == 0] <- NA
This returns:
> df
a new
1 0.0 NA
2 87.3 88
3 88.1 88
4 81.7 82
5 79.2 80
6 89.4 90
There are two options. Suppose you have toy data:
set.seed(0); x <- round(runif(10, 1, 5),1) ## toy data
# [1] 4.6 2.1 2.5 3.3 4.6 1.8 4.6 4.8 3.6 3.5
You can do either of the two:
ceiling(x) - ceiling(x) %% 2
# [1] 4 2 2 4 4 2 4 4 4 4
floor(x) + floor(x) %% 2
# [1] 4 2 2 4 4 2 4 4 4 4
So for your data frame, you might do:
df$new <- floor(df$a) + floor(df$a) %% 2
df$new[df$a == 0] <- NA
where the final line setting NA
part is easy to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With