[R] nth kludge
Jan van der Laan
rhe|p @end|ng |rom eoo@@dd@@n|
Thu Mar 9 10:19:23 CET 2023
Hi Avi, list,
Below an alternative suggestion:
func <- function(a, b, c) {
list(a, b, c)
}
1:3 |> list(x = _) |> with(func(a, x, b))
Not sure if this is more readable than some of the other solutions, e.g.
your solution, but you could make a variant of with more specific for
this use case:
named <- function(expr, ...) {
eval(substitute(expr), list(...), enclos = parent.frame())
}
then you can do:
1:3 |> named(func(1, x, mean(x)), x= _)
or perhaps you can even simplify further using the same strategy:
dot <- function(., expr) {
eval(substitute(expr), list(. = .), enclos = parent.frame())
}
1:3 |> dot(func(1, ., mean(.)))
This seams simpler than the lambda notation and more general than your
solution. Not sure if this has any drawbacks.
HTH,
Jan
On 08-03-2023 21:23, avi.e.gross using gmail.com wrote:
> I see many are not thrilled with the concise but unintuitive way it is
> suggested you use with the new R pipe function.
>
> I am wondering if any has created one of a family of functions that might be
> more intuitive if less general.
>
> Some existing pipes simply allowed you to specify where in an argument list
> to put the results from the earlier pipeline as in:
>
> . %>% func(first, . , last)
>
> In the above common case, it substituted into the second position.
>
> What would perhaps be a useful variant is a function that does not evaluate
> it's arguments and expects a first argument passed from the pipe and a
> second argument that is a number like 2 or 3 and a third argument that is
> the (name of) a function and remaining arguments.
>
> The above might look like:
>
> . %>% the_nth(2, func, first , last)
>
> The above asks to take the new implicitly passed first argument which I will
> illustrate with a real argument as it would also work without a pipeline:
>
> the_nth(piped, 2, func, first, last)
>
> So it would make a list out of the remaining arguments that looks like
> list(first, last) and interpolate piped at position 2 to make list(first,
> piped, last) and then use something like do.call()
>
> do.call(func, list(first, piped, last))
>
> I am not sure if this is much more readable, but seems like a
> straightforward function to write, and perhaps a decent version could make
> it into the standard library some year that is general and more useful than
> the darn anonymous lambda notation.
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list