【发布时间】:2023-04-03 01:28:01
【问题描述】:
“想要的”结果由下面的“do”函数给出。我认为我可以通过使用 unnest 来获得相同的效果,但无法让它发挥作用。
library(dplyr)
library(tidyr)
# Function rr is given
rr = function(x){
# This should be an expensive and possibly random function
r = range(x + rnorm(length(x),0.1))
# setNames(r, c("min", "max")) # fails, expecting single value
# list(min = r[1], max= r[2]) # fails
list(r) # Works, but result is in "long" form without min/max
}
# Works, but syntactically awkward
iris %>% group_by(Species) %>%
do( {
r = rr(.$Sepal.Width)[[1]]
data_frame(min = r[1], max = r[2])
})
# This give the long format, but without column
# names min/max
iris %>% group_by(Species) %>%
summarize(
range = rr(Sepal.Length)
) %>% unnest(range)
【问题讨论】:
-
@Bulat:上面的例子完全可以重现。此外,它被剥离了所有不必要的混乱。因此我不明白你的评论。
-
我不知道 iris 数据集,我猜缺少的是所需的结果或有关不工作的详细信息。您提供了两个工作代码示例,不清楚哪里出了问题。
-
第一个例子根本不是优雅的代码,即使结果是正确的。运行第二个,看看有什么不同。
-
我认为目前这个问题没有好的解决方案。