Carol Eisen
Carol Eisen

Reputation: 608

dplyr return ALL columns

I just started using dplyr and tidyr and have a question:

I have data frame with columns A, B, C and D. I want to mutate all values in columns B and C in place or return all columns after selecting B and C. Eg.

data <- data %>%
    dplyr::select(select=B:C) %>%
    dplyr::mutate_if(is.character, stringr::str_replace_all,
        pattern = "x", replacement = "y")

I want data to include ALL columns in the end and the select command only to affect the following operations and not actually subset the data frame. How do I do that?

Upvotes: 1

Views: 253

Answers (1)

Edo
Edo

Reputation: 7818

Few points:

  • you can call the library once instead of using dplyr:: each time.
  • I'm not sure if you need that is.character since you just asked to apply your function to B and C
  • I suggest you to use across which has superseded the use of mutate_if [starting from dplyr >= 1.0.0]
library(dplyr)
data <- data %>%
    mutate(across(c(B,C), stringr::str_replace_all,
           pattern = "x", replacement = "y"))

Upvotes: 2

Related Questions