Max
Max

Reputation: 407

Round data to the nearest even integer

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

Upvotes: 6

Views: 6046

Answers (2)

Zheyuan Li
Zheyuan Li

Reputation: 73265

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.

Upvotes: 5

Patrick Roocks
Patrick Roocks

Reputation: 3259

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

Upvotes: 8

Related Questions