purrr :: pmap与dplyr :: mutate [英] purrr::pmap with dplyr::mutate
本文介绍了purrr :: pmap与dplyr :: mutate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个接受多个输入并创建多个输出的函数。例如:
I have a function which takes multiple inputs and creates multiple outputs. For example:
example_fun = function(a,b){
x = a+b
y = a-b
return(list(x=x, y=y))
}
如何使用dplyr :: mutate在数据帧的每一行上评估此功能?转
How can I use dplyr::mutate to evaluate this function on each row of a dataframe? Turn
df = expand.grid(a=c(7,8), b=c(9,10))
df
a b
1 7 9
2 8 9
3 7 10
4 8 10
进入
a b x y
1 7 9 16 -2
2 8 9 17 -1
3 7 10 17 -3
4 8 10 18 -2
以下代码几乎完成了该操作:
this following code almost accomplishes it:
df = df %>%
mutate(outputs = pmap(list(a,b), example_fun)) %>%
unnest()
df
a b outputs
1 7 9 16
2 7 9 -2
3 8 9 17
4 8 9 -1
5 7 10 17
6 7 10 -3
7 8 10 18
8 8 10 -2
推荐答案
稍作更改:
example_fun = function(a, b) {
x = a + b
y = a - b
return(data_frame(x = x, y = y)) #data_frame, not list
}
df <- data_frame(a = sample(1:5, 10, rep = TRUE), b = 11:20) #made my own test dataset
df %>%
mutate(outputs = map2(a, b, example_fun)) %>% #I use map2 rather than pmap
unnest()
这篇关于purrr :: pmap与dplyr :: mutate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文