简体   繁体   中英

How to vectorize this code r code using dplyr

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.

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"))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM