繁体   English   中英

如何使用 dplyr 向量化此代码 r 代码

[英]How to vectorize this code r code using dplyr

我想知道如何通过向量化来缩短这段代码(活动是长度为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))

我想要类似mutate(label=recode(label, 1:3 = activities)

rename_with( ~ gsub(c("^t", ^f", "Acc"), c("Time","Frequency","Accelerometer"), .x)) ,但这些不起作用。谢谢。

我们可以在recode中使用命名向量来更改值

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

关于rename_withgsub没有针对patterns进行矢量化。 相反,我们可以使用str_replace

library(stringr)

   ... %>%
        rename_with(~  str_replace_all(.x, setNames( c("Time","Frequency","Accelerometer"), c("^t", "^f", "Acc"))))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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