首页 > 解决方案 > 在R代码中使用样式器将T替换为TRUE,F替换为FALSE

问题描述

library("styler")
myugly_code <- "if ( x==T ) print( 'y' )"
style_text(myugly_code)
#> if (x == T) print("y")

reprex 包(v0.3.0)于 2020 年 1 月 13 日创建

我承认在编写代码时我们应该始终使用TRUEorFALSE而不是Tand 。但是,在编辑以前的代码或其他人用and编写的代码时,是否可以使用包替换 all and with and 。在上面的代码中,我想得到:FRTFstylerTFTRUEFALSE

#> if (x == TRUE) print("y")

标签: r

解决方案


我不知道 styler,但你可以'T''TRUE'using替换gsub。该'\\b'字符是一个单词边界,因此只有'T'在每一侧都有一个单词边界的 a 被替换,而不是例如'T'in 'Test'

sub_TF <- function(s){
  s <- gsub('\\bT\\b', 'TRUE', s)
  gsub('\\bF\\b', 'FALSE', s)
}

sub_TF("list(T, 'Test', F, 'Fox')")
# [1] "list(TRUE, 'Test', FALSE, 'Fox')"

推荐阅读