2

I have data like (a,b,c)

a b c
1 2 1
2 3 1
9 2 2
1 6 2

where 'a' range is divided into n (say 3) equal parts and aggregate function calculates b values (say max) and grouped by at 'c' also.

So the output looks like

a_bin  b_m(c=1) b_m(c=2)
1-3     3          6
4-6     NaN        NaN
7-9     NaN        2

Which is MxN where M=number of a bins, N=unique c samples or all range

How do I approach this? Can any R package help me through?

3 Answers3

3

A combination of aggregate, cut and reshape seems to work

df <- data.frame(a = c(1,2,9,1),
                 b = c(2,3,2,6),
                 c = c(1,1,2,2))

breaks <- c(0, 3, 6, 9)

# Aggregate data
ag <- aggregate(df$b, FUN=max,
                by=list(a=cut(df$a, breaks, include.lowest=T), c=df$c))

# Reshape data
res <- reshape(ag, idvar="a", timevar="c", direction="wide")
nico
  • 50,859
  • 17
  • 87
  • 112
2

There would be easier ways.

If your dataset is dat

res <- sapply(split(dat[, -3], dat$c), function(x) {
a_bin <- with(x, cut(a, breaks = c(1, 3, 6, 9), include.lowest = T, labels = c("1-3", 
    "4-6", "7-9")))
c(by(x$b, a_bin, FUN = max))
})
res1 <- setNames(data.frame(row.names(res), res), 
        c("a_bin", "b_m(c=1)", "b_m(c=2)"))
row.names(res1) <- 1:nrow(res1)

 res1
 a_bin b_m(c=1) b_m(c=2)
1   1-3        3        6
2   4-6       NA       NA
3   7-9       NA        2
akrun
  • 874,273
  • 37
  • 540
  • 662
2

I would use a combination of data.table and reshape2 which are both fully optimized for speed (not using for loops from apply family).

The output won't return the unused bins.

v <- c(1, 4, 7, 10) # creating bins 
temp$int <- findInterval(temp$a, v)

library(data.table)
temp <- setDT(temp)[, list(b_m = max(b)), by = c("c", "int")]

library(reshape2)
temp <- dcast.data.table(temp, int ~ c, value.var = "b_m")
## colnames(temp) <- c("a_bin", "b_m(c=1)", "b_m(c=2)") # Optional for prettier table
## temp$a_bin<- c("1-3", "7-9") # Optional for prettier table

##   a_bin b_m(c=1) b_m(c=2)
## 1   1-3        3        6
## 2   7-9       NA        2
Arun
  • 116,683
  • 26
  • 284
  • 387
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • @Arun, I know that, just keep forgetting :) Although they have a new team member in RStudio who is [rewriting `reshape2` with C++](http://blog.rstudio.org/2014/05/09/reshape2-1-4/) – David Arenburg Jun 28 '14 at 20:07