同时在R中的两个列表上循环 [英] Loop simultaneously over two lists in R

查看:25
本文介绍了同时在R中的两个列表上循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个带有三个参数的函数:

I have written a function that takes three arguments:

create.template <- function(t.list, x, y){
    temp <- cbind(get(t.list[x]), get(t.list[y]), NA)
}

此函数的输出是一个11列17行的data.frame.

The output of this function is a data.frame with 11 columns and 17 rows.

现在,我想用两个列表在函数上创建一个循环,一个用于x,一个用于y.从而

Now I would like to create a loop over the function with two lists, one for x and one for y. Thereby

x.list <- list(1,2,3)
y.list <- list(4,5,6)

在最后一步中,我想建立类似的东西

In the final step I would like to establish something like

for (x in x.list and y in y.list){
   create.template(t.list, x, y)
}

,并有可能在一个最终数据帧中按行组合生成的数据帧(3个数据帧,每个11列).

and possibly combine the resulting dataframes (3 dataframes with 11 columns each) rowwise in one final dataframe.

我知道您可以使用zip()函数在Python中执行此操作,然后通过append()和concatenate()轻松附加结果,但是到目前为止,我还没有找到R中的等效项.非常感谢您的帮助!

I know that you can do this in Python with the zip() function and then append the results easily by append() and concatenate(), but I have not found an equivalent in R so far. Any help is highly appreciated!

推荐答案

我们可以使用 mget 获取多个对象的值,或者使用 Reduce do.call 绑定到 vectors

We can get the values of multiple objects with mget, use either Reduce or do.call to cbind the list of vectors

Reduce(cbind, c(mget(ls(pattern = "\\.list")), NA))

do.call(cbind, c(mget(c("x.list", "y.list")), NA))

这篇关于同时在R中的两个列表上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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