Ric S
Ric S

Reputation: 9247

R - mutate a subset of columns only on a subset of rows

My goal is to modify the values of certain columns (chosen through their names) only on a subset of rows that verify a certain condition, using dplyr.

I have this toy dataframe

library(dplyr)
set.seed(42)
df1 <- data.frame(
  Date = rep(seq.Date(as.Date("2020-01-01"), as.Date("2020-01-31"), "day"), each = 24),
  A1 = runif(744, min = 0, max = 1000),
  A2 = runif(744, min = 0, max = 1000),
  B1 = runif(744, min = 0, max = 1000),
  B2 = runif(744, min = 0, max = 1000)
)

Let's say I want to multiply by 0.2 the values of the columns that start with the letter "B" only in the rows whose Date is either 2020-01-01 or 2020-01-06. The code in this case is pretty simple:

df2 <- df1 %>% 
  mutate(
    B1 = if_else(Date %in% as.Date(c("2020-01-01", "2020-01-06")), 0.2 * B1, B1),
    B2 = if_else(Date %in% as.Date(c("2020-01-01", "2020-01-06")), 0.2 * B2, B2)
  )

However, if I have a lot of variables starting with the letter "B" I want to do this in an automatic way. I've tried mutate_at in the following chunk of code

df2 <- df1 %>% 
  mutate_at(
    vars(starts_with("B")),
    if_else(Date %in% as.Date(c("2020-01-01", "2020-01-06")), 0.2 * ., .)
  )

but R gives me the following error:

Error in Date %in% as.Date(c("2020-01-01", "2020-01-06")) : 
object "Date" not found

What am I doing wrong? I've looked at this question but I would like to find a way that does not define a custom function.

Upvotes: 2

Views: 819

Answers (1)

astrofunkswag
astrofunkswag

Reputation: 2698

See this post for more info

df1 %>%
  mutate_at(vars(starts_with("B")),
            .funs = list(~ if_else(Date %in% as.Date(c("2020-01-01", "2020-01-06")), 0.2 * ., .)))

Upvotes: 2

Related Questions