hhattiecc
hhattiecc

Reputation: 159

Customising intervals/bins with the cut function to tabulate data

I have a variable which I want to use in a contingency table, and so I want to cut the variable's (discrete) values into bins (or rather intervals) which I can then sort my data from a population into. However, I cannot find anyway online that allows me to choose my bins in the following way:

[-30, -20)   [-20, -10)   [-10, 0)   0   (0, 10]   (10, 20]   (20, 30]

i.e. I want some intervals to be left open and right closed, some the other way around, and in the middle zero being a different category altogether. Is there anyway I can do this? I just want to tabulate data.

Upvotes: 1

Views: 186

Answers (1)

Taylor H
Taylor H

Reputation: 436

I think you will need two calls to cut for this:

x <- sample(-30:30, 1000, replace = TRUE)

The key is using the right parameter to get the closure:

x_lower <- as.character(cut(x, breaks = c(-30,-20,-10,0), right = FALSE))
x_upper <- as.character(cut(x, breaks = c(0,10,20,30), right = TRUE ))

And then combine them with ifelse (they are mutually exclusive and the two sets of intervals cover the whole range except zero so this should be fine):

x_new <- ifelse(is.na(x_lower), ifelse(is.na(x_upper), "0", x_upper), x_lower)

Upvotes: 1

Related Questions