逐行迭代,例如与purrr一起应用 [英] Row-wise iteration like apply with purrr

查看:78
本文介绍了逐行迭代,例如与purrr一起应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用purrr :: map实现逐行迭代?

How do I achieve row-wise iteration using purrr::map?

这是我如何使用标准逐行应用的方法.

Here's how I'd do it with a standard row-wise apply.

df <- data.frame(a = 1:10, b = 11:20, c = 21:30)

lst_result <- apply(df, 1, function(x){
            var1 <- (x[['a']] + x[['b']])
            var2 <- x[['c']]/2
            return(data.frame(var1 = var1, var2 = var2))
          })

但是,这不是太优雅,我更愿意用purrr来做.可能(也可能不会)更快.

However, this is not too elegant, and I would rather do it with purrr. May (or may not) be faster, too.

推荐答案

您可以使用pmap进行逐行迭代.这些列用作您正在使用的任何函数的参数.在您的示例中,您将具有三个参数的函数.

You can use pmap for row-wise iteration. The columns are used as the arguments of whatever function you are using. In your example you would have a three-argument function.

例如,这里pmap使用匿名函数来执行您的工作.列将按照它们在数据集中的顺序传递给函数.

For example, here is pmap using an anonymous function for the work you are doing. The columns are passed to the function in the order they are in the dataset.

pmap(df, function(a, b, c) {
     data.frame(var1 = a + b,
                var2 = c/2) 
     }  ) 

您可以使用 purrr 代字号"short-hand"来实现匿名功能,方法是按顺序引用以两个点开头的数字的列.

You can use the purrr tilde "short-hand" for an anonymous function by referring to the columns in order with numbers preceded by two dots.

pmap(df, ~data.frame(var1 = ..1 + ..2,
                var2 = ..3/2)  ) 

如果要以data.frame(而不是列表)的形式获取这些特定结果,则可以使用pmap_dfr.

If you want to get these particular results as a data.frame instead of a list, you can use pmap_dfr.

这篇关于逐行迭代,例如与purrr一起应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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