[R] Set a zero at minimum row by group

William Dunlap wdunlap at tibco.com
Tue Dec 18 17:45:03 CET 2012


You should show what you tried with aggregate and tapply.

You could use ave():
  > wm <- as.logical(ave(df$T, df$ID, FUN=function(x)x==min(x)))
  > df$x_new <- df$x
  > df$x_new[wm] <- 0
  > df
    ID T x x_new
  1  1 1 1     0
  2  1 2 1     1
  3  1 3 1     1
  4  2 1 1     0
  5  2 4 1     1
  6  3 3 1     0
  7  3 5 1     1
  8  3 6 1     1
  9  3 8 1     1

(The as.logical is there because ave() coerces the logical output of
FUN to the type of df$T, numeric, and we need to convert it back to
logical.)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Carlos Nasher
> Sent: Tuesday, December 18, 2012 6:10 AM
> To: r-help at r-project.org
> Subject: [R] Set a zero at minimum row by group
> 
> Dear R Helpers,
> 
> I'm struggling with a data preparation problem. I feel that it is a quite
> easy task but I don't get it done. I hope you can help me with that.
> 
> I have a data frame looking like this:
> 
> ID <- c(1,1,1,2,2,3,3,3,3)
> T <- c(1,2,3,1,4,3,5,6,8)
> x <- rep(1,9)
> df <- data.frame(ID,T,x)
> 
> >df
> ID T x
> 1 1 1
> 1 2 1
> 1 3 1
> 2 1 1
> 2 4 1
> 3 3 1
> 3 5 1
> 3 6 1
> 3 8 1
> 
> I want to manipulate the x column in a way that for each customer (ID) at
> the minimum of T the x value is set to zero. The result should look like
> this:
> 
> ID T x x_new
> 1 1 1     0
> 1 2 1     1
> 1 3 1     1
> 2 1 1     0
> 2 4 1     1
> 3 3 1     0
> 3 5 1     1
> 3 6 1     1
> 3 8 1     1
> 
> I already tried the aggregate() and apply() function, but I don't get the
> result I'm looking for. I would glad if you could help me out.
> 
> Best regards,
> Carlos
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list