使用R中的函数的额外参数进行归约 [英] Reduce with extra arguments to the function in R

查看:99
本文介绍了使用R中的函数的额外参数进行归约的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在R中使用Reduce函数在多个数据帧之间使用merge函数.问题是,我想将合并函数与参数all=T一起使用,并且似乎无处可以在高阶Reduce函数中指定此函数.

I'm trying to use the Reduce function in R to use the merge function across multiple dataframes. The problem is, I would like to use the merge function with the argument all=T, and there seems to be nowhere to specify this in the higher-order Reduce function.

所以我想:

a <- data.frame(id=c(1, 2, 3, 4), a=c('a', 'b', 'c', 'd'))
b <- data.frame(id=c(1, 2, 5, 6), b=c('a', 'b', 'e', 'f'))
c <- data.frame(id=c(3, 4, 5, 6), c=c('c', 'd', 'e', 'f'))

out <- Reduce(merge, list(a, b, c), all=T)

out
  id    a    b   c
1  1    a    a <NA>
2  2    b    b <NA>
3  3    c <NA>   c
4  4    d <NA>   d
5  5 <NA>    e   e
6  6 <NA>    e   e

但是因为merge默认为all=F,所以我得到的是:

But because merge defaults to all=F, what I'm getting is:

[1] id a  b  c 
<0 rows> (or 0-length row.names)

推荐答案

据我所知,Reduce尚无法处理要传递给函数参数的额外参数.但是您可以使用自定义参数重新定义merge函数,并将其作为匿名函数传递给Reduce:

As far as I know, Reduce can not handle extra parameters to be passed to the function parameter yet. But you can redefine the merge function with customized parameters and pass it as an anonymous function to Reduce:

Reduce(function(x, y) merge(x, y, by = "id", all = T), list(a, b, c))

#  id    a    b    c
#1  1    a    a <NA>
#2  2    b    b <NA>
#3  3    c <NA>    c
#4  4    d <NA>    d
#5  5 <NA>    e    e
#6  6 <NA>    f    f

这篇关于使用R中的函数的额外参数进行归约的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆