0

I'm trying to find the row wise max of columns selected using a vector of column names. However, dplyr doesn't seem to accept a vector of names which each have "" around them.

Here's the code I'm using.

ladder.channel <- c("channel_4")
bleed.channels <- c("channel_1", "channel_2", "channel_3", "channel_5")
  
  y <- x %>%
    mutate(correction = -pmax(bleed.channels)) %>%
    mutate(channel.corr = ladder.channel + correction)

But I get this error:

    Error: Problem with `mutate()` column `correction`.
ℹ `correction = -pmax(bleed.channels)`.
x invalid argument to unary operator
Backtrace:
 1. `%>%`(...)
 8. base::.handleSimpleError(...)
 9. dplyr:::h(simpleError(msg, call))

Any idea how to get dplyr to accept a vector to select column names. I've read a few posts, including using all_of, but can't get it working (How to call column names from an object in dplyr?, Use dynamic variable names in `dplyr`)

Mike
  • 921
  • 7
  • 26
  • You can use `... %>% rowwise() %>% mutate(max_val = max(across(all_of(bleed.channels))))` or `... %>% mutate(correction = pmax(!!!syms(bleed.channels)))`. – Ritchie Sacramento Sep 01 '21 at 09:01
  • It looks like your error is generated by the `-pmax(bleed.channels)` bit, so it doesn't seem to be a `dplyr` issue. – Claudio Sep 01 '21 at 09:07
  • Great thanks @27-ϕ-9, both of these work, though I'm not sure what !!!syms is doing. I've now got a problem with the second line though, as if I use !!!syms with `ladder.channel`, it won't let me specify the `correction` column! – Mike Sep 01 '21 at 09:14
  • I don't think that this issue should have been closed. `library(dplyr) x <- data.frame( channel_1 = c(1,2,3), channel_2 = c(4,5,6), channel_3 = c(7,8,9) ) ladder.channel <- c("channel_1") bleed.channels <- c("channel_2", "channel_3") x %>% mutate( correction = -pmax(!!!syms(ladder.channel)) ) %>% rowwise() %>% mutate(channel.corr = sum(correction, !!!syms(bleed.channels))) `. I can now not format it correctly. However, you need to then perform `rowwise()` and again use `!!!syms()`. – MKR Sep 01 '21 at 09:21
  • You can do `... %>% mutate(correction = -pmax(!!!syms(vars)), channel.corr = !!sym(ladder.channel) + correction) `. – Ritchie Sacramento Sep 01 '21 at 09:24
  • Thanks everyone, I've now got the channel.corr mutation working with `rowwise() %>% mutate(channel.corr = sum(across(all_of(c(ladder.channel, "correction")))))`. However, it's so slow! Is there a way that's gets around the calculation burden of `rowwise()`? – Mike Sep 01 '21 at 13:42

0 Answers0