coding variable values into classes using R
The cut
method as outlined by @Greg is probably what you want here. One thing to note is that cut
returns a factor by default, which you can suppress by supplying labels = FALSE
to return the integer values:
cut(data$wt, c(178, 200, 300, Inf), labels = FALSE)
Alternatively, if your cutting does not lend itself to natural breaks, you can use ifelse()
. You can "nest" the ifelse statements similar to Excel. I use "with" to cut down on the typing needed:
data$group2 <- with(data, ifelse(wt >= 179 & wt < 200, 1, ifelse(wt >= 200 & wt < 300, 2, 3)))
You can try cut
anim <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) wt <-c(181,179,180.5,201,201.5,245,246.4,189.3,301,354,369,205,199,394,231.3) data <- data.frame(anim,wt)
EDIT: fixed group - right = FALSE, got rid of split example.
group = cut(data$wt, c(178, 200, 300, Inf), right=FALSE)data$swt = as.numeric(group)data anim wt swt1 1 181.0 12 2 179.0 13 3 180.5 14 4 201.0 25 5 201.5 26 6 245.0 27 7 246.4 28 8 189.3 19 9 301.0 310 10 354.0 311 11 369.0 312 12 205.0 213 13 199.0 114 14 394.0 315 15 231.3 2>