Skip to content

loop of quartile groups

3 messages · Charles Determan Jr, Rui Barradas, David Winsemius

#
Hello,

There's no function cut2() but it's not very difficult to write one. 
I've named your data example 'dat', it saves keystrokes.
Try the following.

dat <- structure(...etc...)

cut2 <- function(x, g = 0){
     cut(x, breaks = c(-Inf, seq(min(x), max(x), length.out = g)))
}

fun <- function(x) {
     ct <- cut2(x, g = 4)
     factor(ct, levels = levels(ct), labels=1:4)
}

tmp <- sapply(dat[-1], fun)
colnames(tmp) <- paste("quartile", colnames(tmp), sep="_")
dat2 <- cbind(dat, tmp)
str(dat2)


Hope this helps,

Rui Barradas
Em 17-10-2012 15:23, Charles Determan Jr escreveu:
#
On Oct 17, 2012, at 7:23 AM, Charles Determan Jr wrote:

            
require(Hmisc)  # which is the package that provides cut2
  dat$quart_var1 <- factor( cut2( dat$var1, g=4), labels=1:4)
  dat
#------------------
       ID var1 var2   var3 var4 quart_var1
1  11112  106    0  70.67  136          3
2  11811  107    0  81.33  139          3
3  12412  116  201  93.67  142          3
4  12510   67  558  84.33  138          1
5  13111   76  526  52.00  140          2
6  20209  146  555  74.00  140          4
7  20612   89  576 114.00  136          2
8  20711   62    0 101.00  139          1
9  21510   65  531  80.33  140          1
10 22012  116  649  91.33  139          3

That won't generalize well, so you could work with this version of the  
same operation:

dat[paste("quart", names(dat)[2], sep="_")] <-  
factor( cut2( dat[[ names(dat)[2] ]], g=4), labels=1:4)