Mike
Mike

Reputation: 1141

Is there a quicker way to rowwise sum across selected columns in a data frame?

I'm using dplyr to sum rowwise across selected columns in a data frame. Because I'm using a character vector to specify the columns, it seems I need to use rowwise, which seems to be very calculation heavy and takes ages across my big data frame (>15 min). Does anyone know of a quicker way please!?

x <- data.frame("channel_1" = seq(1, 10),
                "channel_2" = seq(1, 10),
                "channel_3" = seq(1, 10),
                "channel_4" = seq(1, 10),
                "channel_5" = seq(1, 10))

ladder.channel <- "channel_4"
bleed.channels <- setdiff(c("channel_1", "channel_2", "channel_3", "channel_4", "channel_5"), ladder.channel)
  y <- x %>%
    mutate(correction = -pmax(!!!syms(bleed.channels))) %>%
    rowwise() %>%
    mutate(channel.corr = sum(across(all_of(c(ladder.channel, "correction")))))

Upvotes: 0

Views: 93

Answers (1)

r2evans
r2evans

Reputation: 160437

Does this work?

x %>%
  mutate(
    correction = -pmax(!!!syms(bleed.channels)),
    channel.corr = !!sym(ladder.channel) + correction
  )

Upvotes: 1

Related Questions