我正在尝试下面的代码来与Julia(1.5.3)一起使用,它只是我正在尝试执行的操作的一种表示形式。
using DataFrames
using DataFramesMeta
using RDatasets
## setup
iris = dataset("datasets", "iris")
gdf = groupby(iris, :Species)
## Applying the split combine
## This code works fine
combine(gdf, nrow, (valuecols(gdf) .=> mean))
但是,当我尝试对多个摘要进行操作时,它会失败
combine(gdf, nrow, (valuecols(gdf) .=> [mean, sum]))
错误:
错误:DimensionMismatch(“数组无法广播到相同的大小;获得了长度为4和2的尺寸”)
关于错误的小调试表明,如果我将代码更改为此:
combine(gdf, nrow, ([:SepalLength, :PetalLength] .=> [mean,sum]))
## This code works but its still not correct as it doesn't tell me the mean and sum of both the columns , rather mean for SepalLength and sum for PetalLength, which was expected as per previous error
对此进行了更多研究,我意识到,我们可以做类似的事情,这个结果是正确的,但是结果是长表格而不是宽表格。我原以为这将为我的问题提供答案,但似乎无法按预期进行。
combine(gdf, ([:SepalWidth, :PetalWidth] .=> x -> ([sum(x), mean(x)])))
## The code above works but output is 6x3 DataFrame, I was expecting 3x6 DataFrame
我的问题是:
有什么方法可以使用分割组合,从而获得如下所示的宽表(我使用“ do end”和“ combine”来生成它)。我对这个解决方案还可以,但是我需要在这里输入所有列,有没有什么办法可以让所有汇总统计信息(总和,中位数,均值等)作为合并中提供的所有列的列。我希望我的问题很清楚,请指出,如果重复或沟通不畅。谢谢
combine(gdf) do x
return(sw_sum = sum(x.SepalWidth),
sw_mean = mean(x.SepalWidth),
sp_mean = mean(x.PetalWidth),
sp_sum = sum(x.PetalWidth)
)
end
## My expected answer should be similar to this
#3×5 DataFrame
# Row │ Species sw_sum sw_mean sp_mean sp_sum
# │ Cat… Float64 Float64 Float64 Float64
#─────┼────────────────────────────────────────────────
# 1 │ setosa 171.4 3.428 0.246 12.3
# 2 │ versicolor 138.5 2.77 1.326 66.3
# 3 │ virginica 148.7 2.974 2.026 101.3
同样,这可行:
combine(gdf, [:1] .=> [mean, sum, minimum, maximum,median])
但这并不会引发上述尺寸错误,仍然让我为之困惑:
combine(gdf, [:1, :2] .=> [mean, sum, minimum, maximum,median])
做:
combine(gdf, nrow, vec(valuecols(gdf) .=> [mean sum]))
或者
combine(gdf, nrow, (valuecols(gdf) .=> [mean sum])...)
或者
combine(gdf, nrow, [n => f for n in valuecols(gdf) for f in [mean sum]])
(请注意,mean
和之间没有逗号sum
)
原因是您需要为广播添加一个额外的维度,.=>
以获取所有输入组合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句