我有像(a,b,c)这样的数据
a b c
1 2 1
2 3 1
9 2 2
1 6 2其中'a‘范围被划分为n个(比如3)相等的部分,聚合函数计算b值(比如max),并按'c’进行分组。
所以输出看起来像这样
a_bin b_m(c=1) b_m(c=2)
1-3 3 6
4-6 NaN NaN
7-9 NaN 2哪一项是所有范围,其中a箱的样本、N=unique c样本或所有范围
我该怎么做呢?有没有什么R包可以帮我呢?
发布于 2014-06-22 18:29:23
aggregate、cut和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-22 18:20:21
会有更简单的方法。
如果数据集为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-22 18:25:30
我将使用data.table和reshape2的组合,它们都针对速度进行了充分的优化(而不是使用apply系列的for循环)。
输出不会返回未使用的回收站。
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 2https://stackoverflow.com/questions/24350113
复制相似问题