Laura
Laura

Reputation: 483

Dplyr: using mutate , across , where and ìfelse to multiple entire column in R

This is my code:

library(vcd)
data(Arthritis)

df<-as.tibble(Arthritis)

df %>% mutate(across(where(~ is.integer(.x) && first(.x) > 50), ~ ifelse(is.integer(.x), .x * 2, .x)))

I would like multiply the entire column that has as the first row a number above 50 and is an integer.

But why its not working? Probably because Im using first(.x).
What am I doing wrong by using first?

Many thanks

Upvotes: 0

Views: 653

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145765

Move the first() logic out of the selection and into the operation, don't duplicate the is.integer check:

df %>% 
  mutate(across(where(is.integer),
         ~ if(first(.x) > 50) {.x * 2} else{.x})
  )

Upvotes: 4

Related Questions