茱莉亚。将一列汇总到具有多列的新 DataFrame

Julia. Summarise one column into a new DataFrame with multiple columns

我需要按一个变量对数据帧进行分组,然后通过添加相对于另一个变量的 .25、.5、.75 分位数的数字或行(我已经可以这样做)和列数来对其进行汇总。

在 R 中我会做例如:

    iris %>%
       group_by(Species) %>%
       summarise(
          quantile(Sepal.Length, c(.25, .75)) %>%
             matrix(nrow = 1) %>%
             as.data.frame() %>%
             setNames(paste0("Sepal.Length", c(.25, .75)))
    )

使用 DataFrames 和 DataFrameMeta 在 Julia 中编写此内容的简洁方法是什么?如果有解决方案可以同时将其应用于多个列,那就更好了。

我能在 Julia 中找到的最接近的解决方案是:

groupby(iris, :Species) |>
   x -> combine(x, :Sepal.Length => x -> [[map(p -> quantile(x, p), (Q25 = 0.25, Q75 = 0.75))] |> DataFrame])

但它只是将数据帧封装到一个单元格中,而它应该将其分散到多个列中。

这是我目前能推荐给你的最短的:

combine(groupby(iris, :Species), :SepalLength => (x -> (quantile(x, [0.25, 0.75]))') => [:q25, :q75])

或类似的

combine(groupby(iris, :Species), :SepalLength => (x -> [quantile(x, [0.25, 0.75])]) => [:25, :q75])

combine(groupby(iris, :Species), :SepalLength .=> [x -> quantile(x, q) for q in [0.25, 0.75]] .=> [:q25, :q75])

但即使是你原来的解决方案似乎也比 R 短一点。我也会将其重写为:

combine(groupby(iris, :Species), :SepalLength => (x -> map(p -> quantile(x, p), (Q25=0.25, Q75=0.75))) => AsTable)

看起来更干净了。

现在,如果您想处理多列,您可以这样做(顺便说一句 - 在 R 中您会怎么做?):

combine(groupby(iris, :Species), [n => (x -> (quantile(x, [0.25, 0.75]))') => [n*"_q25", n*"_q75"] 
                                  for n in ["SepalLength",  "SepalWidth", "PetalLength", "PetalWidth"]])