is there a way to recalculate a set of columns of a df without subsetting and adding them back

Hello,
I have a df where I want to recalculate some columns but do not want to create a subset, just leave them where they are in a df. In the example below "select" does subset the original df, so it would need to be reintroduced into the original df. Is this a necessity, or can be avoided?

library(tidyverse)
mtcars
mtcars1 <- mtcars %>% select(contains("d")) %>% {.*(-1)} 

Here mtcars1 is a subset of mtcars, whereas I would only want to multiply the columns matching my criteria (having "d" in name) by -1 and keep them in mtcars df in their original positions, without extracting them...
Is this doable?

This should work.

library(dplyr)
mtcars %>% mutate(across(contains("d"),  ~ . * -1))
1 Like

Great, many thanks!
When I tried to use contains (admittedly, without across) I got a message that it should go with select :wink:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.