【问题标题】:Replace text or number after a colon in R替换R中冒号后的文本或数字
【发布时间】:2015-11-26 19:48:36
【问题描述】:

我有很多行的文本文件,我想更改(替换)冒号后的值(文本或数字)。例如,我想将一个值(0.0000000)更改为另一个值;将文本更改为值,将文本更改为文本。如何做到这一点,同时又不会弄乱 R 中的数据结构?

我把我的示例数据放在下面。如何做到这一点,同时又不会弄乱 R 中的数据结构?我试过 sub,但没有任何好的结果。

R 数据:

text_data <- c("some parameter : 0.0000000", "another one    : none", "third one      : none")

数据:

some parameter : 0.0000000
another one    : none
third one      : none

结果:

some parameter : 7500.0000000
another one    : 0.0000000
third one      : "Missing Data"

【问题讨论】:

    标签: regex r string substring


    【解决方案1】:

    您可以使用strsplit 函数。

    text_data <- c("some parameter : 0.0000000", 
                   "another one    : none", 
                   "third one      : none")
    
    stext <- strsplit(text_data, ":")
    s1 <- lapply(stext, function(x) x[1])
    s2 <- c("7500.0000000", 0.0000000, "Missing Data")
    
    paste(s1, ":", s2)
    
    # [1] "some parameter  : 7500.0000000"
    # [2] "another one     : 0"           
    # [3] "third one       : Missing Data"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多