Dplyr on a subset of columns while keeping the rest of the data.frame

I am trying to use dplyr to apply a function to a subset of columns. However, unlike the code below, I am trying to implement this by keeping all columns in the dataframe. Currently, the resulting data frame only stores the selected columns. I can use the remove-and-cbind construct to concatenate these columns back into the original dataframe, but I was wondering if there is a way to do this directly in dplyr? I tried to move the select function inside the mutate function but couldn't get it working so far.

require(dplyr)
Replace15=function(x){ifelse(x<1.5,1,x)}
dg <- iris %>%
  dplyr::select(starts_with("Petal")) %>%
  mutate_each(funs(Replace15))  
dg

> dg
Source: local data frame [150 x 2]

   Petal.Length Petal.Width
1           1.0           1
2           1.0           1
3           1.0           1
4           1.5           1
5           1.0           1
6           1.7           1
7           1.0           1
8           1.5           1
9           1.0           1
10          1.5           1

      

+3


source to share


2 answers


dg <- iris %>% mutate_each(funs(Replace15), matches("^Petal"))

      



Alternatively (as posted by @aosmith) you can use starts_with

. Look ?select

for other special features available within select

, summarise_each

andmutate_each.

+3


source


mutate_each

is now deprecated
, replaced by mutate_if

and mutate_at

. Using these substitutions, the answer is



dg <- iris %>% mutate_at(vars(starts_with("Petal")), funs(Replace15))

      

+1


source







All Articles