繁体   English   中英

do.call(rbind,…)是否有更高阶的替代品?

[英]Is there a higher order replacement for do.call(rbind, …)?

考虑以下数据帧A

A <- data.frame(ID = c(1,1,1,2,2,2), num = c(6,2,8,3,3,1))

对于A ,我想分割ID ,然后计算num的差。 可以(几乎)获得所需的结果

do.call(rbind, Map(function(x) { x$new <- c(diff(x$num), NA); x }, 
                   split(A, A$ID)))
#     ID num new
# 1.1  1   6  -4
# 1.2  1   2   6
# 1.3  1   8  NA
# 2.4  2   3   0
# 2.5  2   3  -2
# 2.6  2   1  NA

在R用户中, do.call(rbind, ...)广为流传并不是什么秘密。 但是,通过?Map页面上的高阶函数式编程功能( ReduceFilter等),我认为可能有些我不知道的东西可以替代do.call(rbind, ...)还将在过程中重置行名。 我已经尝试了以下方法。

> Reduce(function(x) { x$new <- c(diff(x$num), NA); x }, Map, split(A, A$ID))
# Error in f(init, x[[i]]) : unused argument (x[[i]])
> Reduce(function(x) { x$new <- c(diff(x$num), NA); x }, split(A, A$ID))
# Error in f(init, x[[i]]) : unused argument (x[[i]])
> Reduce(Map(function(x) { x$new <- c(diff(x$num), NA); x }, split(A, A$ID)))
# Error in Reduce(Map(function(x) { : 
#   argument "x" is missing, with no default

我想要的确切结果是通过

> M <- do.call(rbind, Map(function(x) { x$new <- c(diff(x$num), NA); x }, 
                          split(A, A$ID)))
> rownames(M) <- NULL
> M
#   ID num new
# 1  1   6  -4
# 2  1   2   6
# 3  1   8  NA
# 4  2   3   0
# 5  2   3  -2
# 6  2   1  NA

是否有一个高阶函数可以代替do.call(rbind, ...)并同时合并行名rownames(x) <- NULL

注意:我确实在寻找与?Map相关的答案,但对其他人开放。

你可以看一下rbindlist从“data.table”:

library(data.table)

rbindlist(Map(function(x) { 
  x$new <- c(diff(x$num), NA)
  x}, split(A, A$ID)))
#    ID num new
# 1:  1   6  -4
# 2:  1   2   6
# 3:  1   8  NA
# 4:  2   3   0
# 5:  2   3  -2
# 6:  2   1  NA

但是,纯粹的“ data.table”方法更为直接:

DT <- as.data.table(A)

DT[, new := c(diff(num), NA), by = ID][]
#    ID num new
# 1:  1   6  -4
# 2:  1   2   6
# 3:  1   8  NA
# 4:  2   3   0
# 5:  2   3  -2
# 6:  2   1  NA

可以说,这种plyr -combine方法就是plyr的全部意义所在。 不是在基数R中,而是有效的“高阶”。

library("plyr")
ddply(A,"ID",transform,new=c(diff(num),NA))

dplyr版本(显然不是dplyr transform :必须使用mutate代替...)

library("dplyr")
A %>% group_by("ID") %>% 
     mutate(new=c(diff(num),NA))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM