Dambo
Dambo

Reputation: 3486

How to mutate a subset of columns with dplyr?

I have this tbl

data_frame(a_a = letters[1:10], a_b = letters[1:10], a = letters[1:10])

And I am trying to substitute all d in each column starting with a_ with the value new value.

I thought the below code would do the job, but it doesn't:

data_frame(a_a = letters[1:10], a_b = letters[1:10], a = letters[1:10]) %>% 
  mutate_each(vars(starts_with('a_'), funs(gsub('d', 'new value',.))))

instead it gives

Error: is.fun_list(calls) is not TRUE

Upvotes: 0

Views: 277

Answers (1)

Aramis7d
Aramis7d

Reputation: 2496

Guiding from this similar question and considering dft as your input, you can try :

dft %>%
  dplyr::mutate_each(funs(replace(., . == "d", "nval")), matches("a_"))

which gives:

## A tibble: 10 × 3
#     a_a   a_b     a
#   <chr> <chr> <chr>
#1      a     a     a
#2      b     b     b
#3      c     c     c
#4   nval  nval     d
#5      e     e     e
#6      f     f     f
#7      g     g     g
#8      h     h     h
#9      i     i     i
#10     j     j     j

Upvotes: 1

Related Questions