Skip to content
Prev 396585 / 398502 Next

[External] Using the pipe, |>, syntax with "names<-"

The main challenge in Bert's original problem is that `[` and `[<-` cannot
be called in a pipeline. The obvious solution is to define named versions,
e.g.:

elt <- `[`
`elt<-` <- `[<-`

Then,
[1] "b"
a foo
1 1   a
2 2   b
3 3   c

You could actually also do (using a similar function already defined in
methods)

z |> names() |> el(2) <- "bar"

Iris's _ trick is of course a nice alternative; and this example in ?pipeOp
already covers it:

# using the placeholder as the head of an extraction chain:
mtcars |> subset(cyl == 4) |> lm(formula = mpg ~ disp) |> _$coef[[2]]

While the replacement question is a nice exercise, I am not sure about the
value of emphasizing that you can use pipes to do complex assignments.
Doesn't that defeat the whole purpose of piping? For one thing, it will
necessarily terminate the pipe. Also, it will not work if the starting
value is not a variable. E.g.,
Error in names(data.frame(a = 1:3, b = letters[1:3]))[2] <- "bar" :
  target of assignment expands to non-language object

Duncan's rename() approach, which will just change the column name and
return the modified object, seems more useful as part of a pipeline.

Best,
-Deepayan
On Sun, 21 Jul 2024 at 04:46, Bert Gunter <bgunter.4567 at gmail.com> wrote: