创建一个小标题,其中一列是一个函数 [英] create a tibble where one column is a function
问题描述
让我说一下,小标题是这样的:
lets say I have a tibble which looks like this:
library(tidyverse)
tib <- tibble (a = 1:3, b = 4:6, d = -1:1)
我想在此小标题中添加一列,其中每个条目都是具有参数a,b和d的函数(例如f(x)= a x ^ 2 + b x + d).这意味着(例如)在第一行中,我想添加函数f(x)= 1 x ^ 2 + 4 x -1,依此类推.
I want to add a column to this tibble where each entry is a function with parameters a,b and d (like f(x) = ax^2 + bx +d). This would mean that (e.g) in the first row I would like to add the function f(x) = 1 x ^2 + 4 x -1, and so on.
我尝试了以下操作:
tib2 <- tib %>%
mutate(fun = list(function(x) {a*x^2+b*x+d}))
这不起作用,因为函数不知道a,b和d是什么.
This does not work since the functions do not know what a, b and d are.
我设法使用功能 mapply
lf <- mapply(function(a,b,d){return(function(x){a*x^2 + b*x + d})}, tib$a, tib$b, tib$d)
tib3 <- tib %>%
add_column(lf)
我想知道是否有人知道在tidyverse中这样做的更优雅的方式.感觉有一种方法可以使用 purrr 包中的 map 函数,但是我没有设法使其正常工作.
I was wondering if anyone knows a more elegant way of doing this within the tidyverse. It feels like there is a way using the map function from the purrr package, but I did not manage to get it working.
谢谢
推荐答案
在示例中使用 mutate
时,您将为其提供一个包含一个元素(功能)的列表.因此,此功能已为所有其他行回收.此外,在函数的定义内,它对 a
, b
或 d
没有任何可见性.
When you used mutate
in your example, you were giving it a list with one element (function). So this one function was recycled for all the other rows. Also, inside the definition of the function, it doesn't have any visibility of a
, b
or d
.
您可以改为使用 pmap
,以便每一行都有其自己的功能.
You can instead use pmap
so that each row has its own function.
tib2 <- tib %>%
mutate(
fun = pmap(
list(a, b, d),
~function(x) ..1 * x^2 + ..2 * x + ..3))
tib2
#> # A tibble: 3 x 4
#> a b d fun
#> <int> <int> <int> <list>
#> 1 1 4 -1 <fun>
#> 2 2 5 0 <fun>
#> 3 3 6 1 <fun>
tib2$fun[[1]](1)
#> [1] 4
这篇关于创建一个小标题,其中一列是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!