[R] Re: coding factor replicates

Peter Baker Peter.Baker at cmis.csiro.au
Thu Jan 24 06:02:04 CET 2002


>>>>> "Greg Warnes" == Warnes, Gregory R <gregory_r_warnes at groton.pfizer.com> writes:

    Greg Warnes> How about this.  Its not as 'swish' as Doug's
    Greg Warnes> response, but it might be a little simpler to think
    Greg Warnes> about and adapt...


I get the distinct impression I've missed something here - isn't the
answer just to convert the factor to numeric? eg

> g <- factor(c("A","B","C","B","C","A","C","B","A","A","B"))
> g
 [1] A B C B C A C B A A B
Levels:  A B C 
> 
> gnum <-  as.numeric(g)
> gnum    
 [1] 1 2 3 2 3 1 3 2 1 1 2
>
> gfac <- factor(as.numeric(g))
> gfac
 [1] 1 2 3 2 3 1 3 2 1 1 2
Levels:  1 2 3 
>

Regards
Peter

    Greg Warnes> # show the test vector
    >> tmp
    Greg Warnes>  [1] A B C B C A C B A A B Levels: A B C
    >>
    Greg Warnes> # create a named vector to store the number of
    Greg Warnes> occurences of each level
    >> index <- numeric(length=length(levels(tmp))) names(index) <-
    >> levels(tmp) index
    Greg Warnes>     A B C [1] 0 0 0
    >>
    Greg Warnes> # create a vector to store the results
    >> retval <- numeric(length(tmp))
    >> 
    Greg Warnes> # iterate across the vector, counting the number of
    Greg Warnes> occurences # store the cumulative count in the index
    Greg Warnes> vector and the current count in the result vector
    >> for( i in 1:length(tmp) )
    Greg Warnes> + retval[i] <- index[tmp[i]] <- index[tmp[i]] + 1
    >>
    Greg Warnes> # show the results
    >> retval
    Greg Warnes>  [1] 1 1 1 2 2 2 3 3 3 4 4

    Greg Warnes> -Greg


    >> -----Original Message----- From: Brad Buchsbaum
    >> [mailto:brad at aris.ss.uci.edu] Sent: Wednesday, January 23, 2002
    >> 4:52 PM To: r-help at stat.math.ethz.ch Subject: [R] Re: coding
    >> factor replicates
    >> 
    >> 
    >> 
    >> Hi All,
    >> 
    >> If I have a factor f:
    >> 
    >> A B C B C A C B A A B ....
    >> 
    >> and I would like to generate a factor to indicate the trial
    >> number as a function of condition: e.g.
    >> 
    >> 1 1 1 2 2 2 3 3 3 4 4 ...
    >> 
    >> how might I attack this in R?
    >> 
    >> thanks,
    >> 
    >> Brad Buchsbaum

-- 
Dr Peter Baker, Statistician (Bioinformatics/Genetics),
CSIRO Mathematical & Information Sciences,
120 Meiers Rd, INDOOROOPILLY, QLD 4068.  Australia. 
Email: Peter.Baker at csiro.au
WWW: http://www.cmis.csiro.au/Peter.Baker/
Phone:+61 7 3214 2210   Fax:+61 7 3214 2881
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list