【问题标题】:R: Substituting character strings coerced from numbers in scientific notation with gsubR:用gsub替换从科学计数法数字中强制转换的字符串
【发布时间】:2014-02-24 11:01:10
【问题描述】:

我需要将 som 数据导出到另一种编程语言的文本文件中,其中数字不能超过 14 位。并非所有元素都需要用逗号分隔,所以这就是我使用这种方法的原因。

问题在于gsub 在强制转换为字符串时不会重新转换数字 42,并且科学记数法选项 scipen 设置得足够低,因此 42 会以 E 记数法打印。

这里是scipen=-10,所以 42 以 E 表示法打印。

x <- 4.2e+1    # The meaning of life
options(scipen = -10) 
gsub(pattern=x,replacement=paste(",",x),x,useBytes=TRUE)
[1] "4.2e+01"
gsub(pattern=x,replacement=paste(",",x),x,useBytes=FALSE)
[1] "4.2e+01"

这就像 gsub 没有重新匹配匹配。我也试过了,

gsub(pattern=x,replacement=paste(",",x),as.character(x))

但没有运气。

在以下两个示例中,gsub 的行为符合预期,scipen=0 足够高以确保将 42 打印为 42

x <- 4.2e+1    # Still the meaning of life
options(scipen = 0) 
gsub(pattern=x,replacement=paste(",",x),x,useBytes=TRUE)
[1] ", 42"
gsub(pattern=x,replacement=paste(",",x),x,useBytes=FALSE)
[1] ", 42"

如您所见,useBytes 选项也无济于事。有人可以告诉我我没有得到什么。

谢谢。

【问题讨论】:

    标签: regex r


    【解决方案1】:

    字符.+ 是预定义的正则表达式字符。因此,它们不是按字面解释的。您必须在您的模式中转义这些字符(使用\\)。然后,它会起作用。

    x <- 4.2e+1    # The meaning of life
    options(scipen = -10) 
    
    x_pat <- gsub("(\\+|\\.)", "\\\\\\1", x)
    # [1] "4\\.2e\\+01"
    
    gsub(x_pat, paste(",", x), x)
    # [1] ", 4.2e+01"
    

    另一种可能性是使用参数fixed = TRUE。这将按原样匹配模式字符串。

    gsub(x, paste(",", x), x, fixed = TRUE)
    # [1] ", 4.2e+01"
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 2021-10-30
      • 1970-01-01
      • 2015-12-26
      • 2010-12-15
      • 1970-01-01
      相关资源
      最近更新 更多