简体   繁体   English

R:递归地对列表执行操作

[英]R: Recursively perform operations on a list

I have list of data frames where I am trying to merge all of the elements of the list into a single data frame by applying merge(). 我有数据框列表,我试图通过应用merge()将列表的所有元素合并到一个数据框。 I am looking for a general solution that can handle different functions and large numbers of elements of the list. 我正在寻找一个可以处理不同功能和列表中大量元素的通用解决方案。

For a convenient working example, let's use a related problem that should have the same solution. 为了方便的工作示例,让我们使用应该具有相同解决方案的相关问题。 So, assume we have instead a list of numbers: 所以,假设我们有一个数字列表:

foo <- list(1, 2, 478, 676)

Let's further assume that I am trying to write a script that takes the first number and divides it by the second. 让我们进一步假设我正在尝试编写一个脚本,它接受第一个数字并将其除以第二个数字。 It then takes that quotient and divides it by the third. 然后取出该商并将其除以第三个。 It then takes that quotient and divides it by the fourth, etc. In the end, I have a single number stored in a single object. 然后取出该商并将其除以第四个等等。最后,我将一个数字存储在一个对象中。 For example: 例如:

((foo[1] / foo[2]) / foo[3]) / foo[4]

I have seen rapply() for recursive operations on lists, but all of the examples are for delisting lists and not other operations, such as merge() or arithmetic operations. 我已经看到rapply()用于列表上的递归操作,但所有示例都是用于除名列表而不是其他操作,例如merge()或算术运算。

正如评论中所述,使用Reduce(function, x)工作,其中function是在列表的每个元素上执行的函数, x是列表。

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

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