Consider this simple example:
library(dplyr)
dataframe <- data_frame(helloo = c(1,2,3,4,5,6),
ooooHH = c(1,1,1,2,2,2),
ahaaa = c(200,400,120,300,100,100))
# A tibble: 6 x 3
helloo ooooHH ahaaa
<dbl> <dbl> <dbl>
1 1 1 200
2 2 1 400
3 3 1 120
4 4 2 300
5 5 2 100
6 6 2 100
Here I want to apply the function ntile
to all the columns that contains oo
, but I would like these new columns to be called cat
+ the corresponding column.
I know I can do this
dataframe %>% mutate_at(vars(contains('oo')), .funs = funs(ntile(., 2)))
# A tibble: 6 x 3
helloo ooooHH ahaaa
<int> <int> <dbl>
1 1 1 200
2 1 1 400
3 1 1 120
4 2 2 300
5 2 2 100
6 2 2 100
But what I need is this
# A tibble: 8 x 5
helloo ooooHH ahaaa cat_helloo cat_ooooHH
<dbl> <dbl> <dbl> <int> <int>
1 1 1 200 1 1
2 2 1 400 1 1
3 3 1 120 1 1
4 4 2 300 2 2
5 5 2 100 2 2
6 5 2 100 2 2
7 6 2 100 2 2
8 6 2 100 2 2
Is there a solution that does NOT require to store the intermediate data, and merge back to the original dataframe?