这是一种可能,您可以使用lapply
循环遍历数据框中的列,并sapply
循环遍历值所在的间隔数cut
(“n_int”)。结果列表被melt
编辑为长格式。
均值使用 计算aggregate
,按“L1”(对应于原始数据中的列)、“cut_set”(切割集、2 或 4 个间隔)和“interval”(间隔编号)分组。
# some toy data
d1 <- data.frame(a = 1:10,
b = seq(100, 1000, len = 10))
d1
# a vector of number of intervals
n_int <- 2 * 1:2
library(reshape2)
d2 <- melt(lapply(d1, function(x){
data.frame(x, sapply(n_int, function(i){
as.integer(cut(x, i))
})
)
}),
id.vars = "x", variable.name = "cut_set", value.name = "interval")
d3 <- aggregate(x ~ L1 + cut_set + interval, data = d2, mean)
d3[order(d3$L1, d3$cut_set, d3$interval), ]
# L1 cut_set interval x
# 1 a X1 1 3.0
# 5 a X1 2 8.0
# 3 a X2 1 2.0
# 7 a X2 2 4.5
# 9 a X2 3 6.5
# 11 a X2 4 9.0
# 2 b X1 1 300.0
# 6 b X1 2 800.0
# 4 b X2 1 200.0
# 8 b X2 2 450.0
# 10 b X2 3 650.0
# 12 b X2 4 900.0
另一种使用方式dplyr
:
library(dplyr)
d1 %>%
melt(id.vars = NULL) %>%
group_by(variable) %>%
do(data.frame(., sapply(n_int, function(i) as.integer(cut(.$value, i))))) %>%
melt(id.vars = c("variable", "value"), variable.name = "cut_set", value.name = "interval") %>%
group_by(variable, cut_set, interval) %>%
summarise(mean = mean(value))