函数的无效结果在汇总中返回多个值

时间:2016-05-22 09:27:25

标签: r dplyr tidyr

"想要"结果由" do"功能如下。我认为我可以通过使用不当的方法来获得相同的效果,但无法使其工作。

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)

2 个答案:

答案 0 :(得分:6)

这是使用data.table

的非常简单的替代方案
# Function rr is given
rr = function(x) as.list(setNames(range(x + rnorm(length(x), 0.1)), c("min", "max"))) 

library(data.table)
data.table(iris)[, rr(Sepal.Width), by = Species]
#       Species      min      max
# 1:     setosa 1.839845 6.341040
# 2: versicolor 1.063727 5.498810
# 3:  virginica 1.232525 5.402483

答案 1 :(得分:4)

Unnest()将始终将您的嵌套列重新列入" long"格式,但如果您创建spread()列,则可以使用key获取所需的输出。

library(dplyr)
library(tidyr)

iris %>%
  group_by(Species) %>%
  summarize(range = rr(Sepal.Length)) %>% 
  unnest(range) %>% mutate(newcols = rep(c("min", "max"), 3)) %>%
  spread(newcols, range)
#     Species      max      min
#      (fctr)    (dbl)    (dbl)
#1     setosa 7.636698 3.292692
#2 versicolor 9.792319 3.337382
#3  virginica 9.810723 3.367066