0

我有一个按天和按小时的流量数据集。我编写了一个函数,我想将其应用于该数据集的不同条件。

例如,我想比较一周中不同日子和一天中不同时间的平均流量。

如何使用循环过滤一周中每个可能的日子,并为每个人返回我有函数的指标?

非常感谢这里的一些帮助。

谢谢,
扎克

4

1 回答 1

0

我不确定循环是否适合您尝试做的事情,但这是一种方法。

# generate example data
set.seed(1234)
df <- data.frame(hour    = sample(1:24, 100, T), 
                 dow     = sample(1:7, 100, T), 
                 traffic = round(runif(100, 1, 50)))

# prep storage matrix for results
H <- sort(unique(df$hour))
D <- sort(unique(df$dow))
res_mat <- matrix(NA, nrow=length(H), ncol=length(D))
colnames(res_mat) <- D
rownames(res_mat) <- H

# function I want to apply to subsets of values
my_fun <- function(x) { mean(x) + 2 }

# loop
for(h in seq_along(H)) {
for(d in seq_along(D)) {
    # get vector of traffic for a particular hour and day-of-week combo
    subset_of_traffic <- df[df$hour == H[h] & df$dow == D[d], "traffic"]

    # skip if no traffic data for this hour and day-of-week combo
    if(length(subset_of_traffic)==0) next

    # run function on that subset and store result
    res_mat[h,d] <- my_fun(subset_of_traffic)
}
}

使用 data.table 获得相同结果的更快方法:

library(data.table)
dt <- data.table(df)
res_dt <- dt[ , .(results = my_fun(traffic)), by=.(hour, dow)]
于 2018-07-23T02:38:03.833 回答