从源文件中调用stringr::str_replace_all不能正常工作。

问题描述 投票:0回答:1

file_helper.R作为

library(stringr)
cleanStringFunctionSourced <- function(string) {
result <- stringr::str_replace_all(string, c("ü" = "ue", "ï" = "ie", "ë" = "ee", "ä" = "ae", "ö" = "oe", "ß" = "ss"))
return(paste0("with function from file_helper.R : ", result))
}

test.R 作为 :

library(stringr)
source("file_helper.R")

test_string <- "ü,ï,ë,ä,ö,ß"

cleanStringFunctionLocal <- function(string) {
  result <- stringr::str_replace_all(string, c("ü" = "ue", "ï" = "ie", "ë" = "ee", "ä" = "ae", "ö" = "oe", "ß" = "ss"))
  return(paste0("with same file function : ", result))
}
print(paste0("original string :", test_string))
#> [1] "original string :ü,ï,ë,ä,ö,ß"
print(cleanStringFunctionLocal(test_string))
#> [1] "with same file function : ue,ie,ee,ae,oe,ss"
print(cleanStringFunctionSourced(test_string))
#> [1] "with function from file_helper.R : ü,ï,ë,ä,ö,ß"



    #> R version 3.6.3 (2020-02-29)
    #> Platform: x86_64-w64-mingw32/x64 (64-bit)
    #> Running under: Windows 10 x64 (build 18362)
    #> 
    #> Matrix products: default
    #> 
    #> locale:
    #> [1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252   
    #> [3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C                   
    #> [5] LC_TIME=German_Germany.1252    
    #> 
    #> attached base packages:
    #> [1] stats     graphics  grDevices utils     datasets  methods   base     
    #> 
    #> loaded via a namespace (and not attached):
    #>  [1] compiler_3.6.3  magrittr_1.5    tools_3.6.3     htmltools_0.4.0
    #>  [5] yaml_2.2.1      Rcpp_1.0.3      stringi_1.4.6   rmarkdown_2.1  
    #>  [9] highr_0.8       knitr_1.28      stringr_1.4.0   xfun_0.12      
    #> [13] digest_0.6.25   rlang_0.4.5     evaluate_0.14

当从外部源文件调用时, stringr::str_replace_all 似乎不工作.有人能好心告诉我,我在这里做错了什么吗?Thanks a lot in advance.

r stringr
1个回答
1
投票

检查编码。可能是你的函数 cleanStringFunctionSourced 正确执行,只是字面的u元音没有正确的来源。在您的编辑器中,检查 file_helper.R 被保存 编码,然后在指定正确的编码的同时将其作为源码,如

source('file_helper.R', encoding='utf-8')

UTF8将是一个很好的编码候选。

© www.soinside.com 2019 - 2024. All rights reserved.