函数是否可以在一个数据帧中返回其参数的所有排列? [英] Function to return all permutations of its arguments in one data frame?

查看:75
本文介绍了函数是否可以在一个数据帧中返回其参数的所有排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多年的数据.我有一个函数,该函数需要一个产品名称,一个年份,并从数据库中弹出一个包含各种描述符的数据框.我想将参数传递给函数:

I have data for multiple years. I have a function that takes a product name, a year and spits out a dataframe containing various descriptors from the database. I want to pass into the function the arguments:

Product <- c("A","B")    
Year <- c("2015","2016")

并为其计算这些参数的所有排列,并返回单个数据帧.我已经尝试过使用mapply和rbind,但是结果却很混乱.有什么建议吗?

and for it to calculate all permutations of those arguments, returning a single dataframe. I've tried using mapply and rbind but it turns out all messy. Any advice?

推荐答案

您可以结合使用tidyr中的crossing,purrr中的pmap和tidyr中的unnest:

You can use a combination of crossing from tidyr, pmap from purrr, and unnest from tidyr:

library(tidyr)
library(purrr)

crossings <- crossing(Product, Year)
crossings$result <- pmap(crossings, find_product_sales)
crossings <- unnest(crossings, result)

正如您在评论中所述,这是假设find_product_sales函数采用乘积和年份并返回数据框.

This is assuming, as you describe in the comments, that the find_product_sales function takes a product and year and returns a data frame.

(请注意,您可以使用expand.grid代替crossing,但是您可能还希望添加stringsAsFactors = FALSE).

(Note that you could use expand.grid instead of crossing, but you'd probably want to add stringsAsFactors = FALSE as well).

这篇关于函数是否可以在一个数据帧中返回其参数的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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