2

I want to know how to shorten this code by vectorizing (activities is a character vector of length 3):

data %>% mutate(label=recode(label, `1`=activities[1],
                                    `2`=activities[2],
                                    `3`=activities[3])) %>%
    rename_with( ~ gsub("^t", "Time", .x)) %>%
    rename_with( ~ gsub("^f", "Frequency", .x)) %>%
    rename_with( ~ gsub("Acc", "Accelerometer", .x))

I want something like mutate(label=recode(label, 1:3 = activities) and

rename_with( ~ gsub(c("^t", ^f", "Acc"), c("Time","Frequency","Accelerometer"), .x)), but these don't work. Thanks.

pskola
  • 23
  • 5
  • Hey. Please provide a reproducible example for us to help you. See for example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Julian_Hn Jul 18 '20 at 18:44
  • https://github.com/pskola/G-CDproject/blob/master/sample_data.txt Here's the sample data. Is github a common place to host their examples, or should I have used something else? – pskola Jul 19 '20 at 02:43

1 Answers1

3

We can use a named vector in recode to change the values

library(dplyr)
data %>%
       mutate(label = recode(label, !!! setNames(activities[1:3], 1:3))) %>%
       rename_at(vars(matches('^([tf]|Acc)')), 
             ~ c("Time", "Frequency", "Accelerometer"))

Regarding rename_with, the gsub is not vectorized for patterns. Instead, we can use str_replace

library(stringr)

   ... %>%
        rename_with(~  str_replace_all(.x, setNames( c("Time","Frequency","Accelerometer"), c("^t", "^f", "Acc"))))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thanks, that's exactly what I meant. I'm not familiar with the !!! notation. Is it a dplyr thing? – pskola Jul 19 '20 at 02:15
  • @pskola it is for splicing and doing the match with the original vector to match and replace – akrun Jul 19 '20 at 18:51