[R] Specification of factors in tapply

Peter Dalgaard BSA p.dalgaard at pubhealth.ku.dk
Wed Feb 21 19:12:50 CET 2001


Hedderik van Rijn <rijn at swi.psy.uva.nl> writes:

> Second, what are the functions/methods I could use to get these results in a
> more R-ish way? I quite often want to perform some function per subset of a
> dataframe and include the results back into the frame. As in the example I
> sent, finding the first value equal to or larger than 0 per
> subject/condition combination.
> 
> Thanks a lot for all the help sofar,
>    Hedderik.
> 
> (Just to be sure, I include the example again:)
> 
> x <- as.data.frame(list(data=c(-9,0,3,1,-9,1,0,-9,0,3,1,-9,1,0),
>                    subj=c(rep(1,7),rep(2,7)),
>                    cond=rep(c(rep(1,4),rep(2,3)),2)))
> 
> x$first <- unlist(tapply(x$data,list(x$subj,x$cond),
>                        function(x) {
>                          retval<-rep(F,length(x));
>                          if (length(x[x>=0])>0) {
>                            retval[min(which(x>=0))]<-T;
>                          }
>                          print(cbind(x,retval)); # Print some debug info
>                          retval}))

It looks a bit unsafe to rely on the storage order in x. I'd go for
brute force and ignorance:

tb <- tapply(x$data,list(x$subj,x$cond),
 function(x) {
      retval<-rep(F,length(x));
      if (any(x>=0)) {
          retval[which(x>=0)[1]]<-T;
      }
      retval
 }

x$first<-NA
for (i in 1:2) 
    for (j i 1:2)
	x$first[x$subj==i & x$cond==j] <- tb[i,j]


or maybe something like.

fct <- function(x) {
      retval<-rep(F,length(x));
      if (any(x>=0)) {
          retval[which(x>=0)[1]]<-T;
      }
      retval
 }

grp <- interaction(x$subj,x$cond)
x$first <- NA
for (i in levels(grp))
   x$first[grp==i] <- fct(x$first[grp==i])

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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