我已经看到了一些关于如何使用dplyr
函数编写自己的函数的文章。例如,您可以看到如何在this post中使用group_by (regroup)
和summarise
。我认为看看我是否可以使用主要dplyr
函数编写函数会很有趣。我的希望是我们可以进一步了解如何使用dplyr
函数编写函数。功能中的主要dplyr函数
DATA
country <- rep(c("UK", "France"), each = 5)
id <- rep(letters[1:5], times = 2)
value <- runif(10, 50, 100)
foo <- data.frame(country, id, value, stringsAsFactors = FALSE)
目标
我想写以下过程中的功能。
foo %>%
mutate(new = ifelse(value > 60, 1, 0)) %>%
filter(id %in% c("a", "b", "d")) %>%
group_by(country) %>%
summarize(whatever = sum(value))
TRY
### Here is a function which does the same process
myFun <- function(x, ana, bob, cathy) x %>%
mutate(new = ifelse(ana > 60, 1, 0)) %>%
filter(bob %in% c("a", "b", "d")) %>%
regroup(as.list(cathy)) %>%
summarize(whatever = sum(ana))
myFun(foo, value, id, "country")
Source: local data frame [2 x 2]
country whatever
1 France 233.1384
2 UK 245.5400
你也许会意识到arrange()
是不存在的。这是我挣扎的人。这里有两点意见。第一个实验是成功的。这些国家的顺序从英法到英法。但第二个实验没有成功。
### Experiment 1: This works for arrange()
myFun <- function(x, ana) x %>%
arrange(ana)
myFun(foo, country)
country id value
1 France a 90.12723
2 France b 86.64229
3 France c 74.93320
4 France d 80.69495
5 France e 72.60077
6 UK a 84.28033
7 UK b 67.01209
8 UK c 94.24756
9 UK d 79.49848
10 UK e 63.51265
### Experiment2: This was not successful.
myFun <- function(x, ana, bob) x %>%
filter(ana %in% c("a", "b", "d")) %>%
arrange(bob)
myFun(foo, id, country)
Error: incorrect size (10), expecting :6
### This works, by the way.
foo %>%
filter(id %in% c("a", "b", "d")) %>%
arrange(country)
鉴于第一个实验是成功的,我很难理解第二个实验失败的原因。在第二次实验中可能有一件事需要做。有没有人有想法?感谢您抽出时间。
Deparsing和粘贴字符串是_永远_写答案。 – hadley 2014-09-23 22:49:48
@hadley ok,在这种情况下,您会推荐“创建列表”方法? – 2014-09-23 22:53:15
我推荐使用'substitute()',或者等待https://github.com/hadley/dplyr/issues/352 – hadley 2014-09-23 22:54:15