 Strawhat - 1 year ago 64
R Question

Ceil and floor values in R

I have a data.table of integers with values between 1 and 60.

My question is about flooring or ceiling any number to the following values: 12 18 24 30 36 ... 60.

For example, let's say my data.table contains the number 13. I want R to "transform" this number into 12 and 18 as 13 lies in between those numbers. Moreover, if I have 18 I want R to keep it at 18.

If my data.table contains the value 50, I want R to convert that number into 48 and 54 and so on.

My goal is to get two different data.tables. One where the floored values are saved and one where the ceiled values are saved.

Any idea how one could do this in R?

EDIT: Numbers smaller than 12 should always be transformed to 12.

Example output:

If have the following data.table

`data.table(c(1,28,29,41,53,53,17,41,41,53))`

I want the following two output data.tables: floored values
`data.table(c(12,24,24,36,48,48,12,36,36,48))`

I want the following two output data.tables: ceiled values
`data.table(c(12,30,30,42,54,54,18,42,42,54))` John Coleman

Here is a fairly direct way (edited to round up to 12 if any values are below):

``````df <- data.frame(nums = 10:20)
df\$floors <- with(df,pmax(12,6*floor(nums/6)))
df\$ceils <- with(df,pmax(12,6*ceiling(nums/6)))
``````

``````> df
nums floors ceils
1    10     12    12
2    11     12    12
3    12     12    12
4    13     12    18
5    14     12    18
6    15     12    18
7    16     12    18
8    17     12    18
9    18     18    18
10   19     18    24
11   20     18    24
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download