R语言 函数(x)如何被包含在document中

xytpbqjk  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(107)

我有一个几年前使用dapr构建的函数。现在由于冲突,我想更新为dapr。dapr::ddply(dataset,by,function(x)与dapr的等价形式是什么?请参见下面:

#Works
intervals <- function(dataset, by, model) {
# code

 ddply(dataset, by, function(x) {
#More code
}
}


#Does not work
intervals <- function(dataset, by, model) {
# code

#How to call function(x) with dplyr? I am getting an error here...
dataset %>% group_by(by) %>% function(x) {
#More code
}
}

Error in dataset %>% group_by(by) %>% function(x) { : 
  invalid formal argument list for "function"

字符串

jgovgodb

jgovgodb1#

mt <- mutate(mtcars, rn = row_number())
res1 <- plyr::ddply(mt, ~ cyl, function(x) mutate(x, disp = disp / max(disp))) %>%
  arrange(rn)

res2 <- mt %>%
  group_by(cyl) %>%
  mutate(disp = disp / max(disp)) %>%
  ungroup() %>%
  arrange(rn)

all.equal(res1, res2, check.attributes=FALSE)
# [1] TRUE

字符串
或者更简洁地说

mt %>%
  mutate(disp = disp / max(disp), .by = cyl)


我创建了rn,然后用它创建了arrange,这只是为了更简单的比较。

相关问题