2

(a,b,c) のようなデータがあります

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

ここで、「a」範囲は n (たとえば 3) の等分部分に分割され、集計関数は b 値 (最大など) を計算し、「c」でもグループ化されます。

したがって、出力は次のようになります

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

MxN で、M=a ビンの数、N=一意の c サンプル、またはすべての範囲

どうすればこれにアプローチできますか? どの R パッケージも私を助けてくれますか?

4

3 に答える 3

3

aggregatecutとの組み合わせがreshapeうまくいくようです

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")
于 2014-06-22T10:29:22.867 に答える
2

data.table私はとの組み合わせを使用しますreshape2が、両方とも速度が完全に最適化されています (ファミリーのforループは使用しません)。apply

出力は未使用のビンを返しません。

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
于 2014-06-22T10:25:30.397 に答える
2

もっと簡単な方法があるでしょう。

データセットが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
于 2014-06-22T10:20:20.740 に答える