【问题标题】:string manipulation in matrix in RR中矩阵中的字符串操作
【发布时间】:2020-12-16 02:36:29
【问题描述】:

我有一个这样的矩阵

A = matrix( 
 c("2 (1-3)", "4 (2-6)", "3 (2-4)", "1 (0.5-1.5)", "5 (2.5-7.5)", "7 (5-9)"), 
nrow=3, 
ncol=2) 

我想用“

B = matrix( 
  c("< 5", "< 5", "< 5", "< 5", "5 (2.5-7.5)", "7 (5-9)"), 
  nrow=3, 
  ncol=2) 

有什么想法吗?

【问题讨论】:

    标签: r string matrix data-manipulation


    【解决方案1】:

    提取第一个数字,将其转换为数字,并将小于5的数字替换为"&lt;5"

    A[as.numeric(sub('(\\d+).*', '\\1', A)) < 5] <- '< 5'
    A
    
    #      [,1]  [,2]         
    #[1,] "< 5" "< 5"        
    #[2,] "< 5" "5 (2.5-7.5)"
    #[3,] "< 5" "7 (5-9)"    
    

    提取第一个数字并将其转换为数字的快捷方式是使用readr::parse_number

    A[readr::parse_number(A) < 5] <- '< 5'
    

    【讨论】:

      【解决方案2】:

      使用 substr() 提取每个矩阵元素的第一个字符。只要那是一个数字,您就可以通过 as.numeric() 将其转换为一个

      A[as.numeric(substr(A,1,1))<5] <- "<5"
      

      【讨论】:

        【解决方案3】:

        1) read.table

        使用read.table 获取每个单元格中的第一个数字,给出向量firstNo。然后使用replace 将这些单元格替换为&lt; 5

        原始输入 A 被保留,这通常是为了使其更易于测试和调试,但如果您更愿意覆盖它,请将第二行代码的左侧替换为 A

        没有使用正则表达式,也没有使用包。

        firstNo <- read.table(text = A)[[1]]
        B <- replace(A, firstNo < 5, "< 5")
        
        B
        

        给予:

             [,1]  [,2]         
        [1,] "< 5" "< 5"        
        [2,] "< 5" "5 (2.5-7.5)"
        [3,] "< 5" "7 (5-9)" 
        

        虽然问题中的示例输入不需要,但如果左括号后的文本可能不规则,那么您可能需要将fill=TRUEcomment.char = "(" 参数添加到read.table

        2) gsubfn

        gsubfn 类似于gsub,只是它将正则表达式中的捕获组,即正则表达式的括号部分,输入到第二个参数中以公式表示法表示的函数中,然后用输出替换匹配项函数。

        library(gsubfn)
        
        B <-  replace(A, 
          TRUE, 
          gsubfn("^(\\d) (.*)", ~ if (as.numeric(x) < 5) "< 5" else paste(x, y), A)
        )
        
        B
        

        给予:

             [,1]  [,2]         
        [1,] "< 5" "< 5"        
        [2,] "< 5" "5 (2.5-7.5)"
        [3,] "< 5" "7 (5-9)" 
        

        【讨论】:

          【解决方案4】:

          如果只有5个选项,我们不需要提取并转换为数字:

          即“0”或“1”或“2”或“3”或“4”

          A[grep("^[0-4]", A)] <- "< 5"
          

          或者

          replace(A, grep("^[0-4]", A), "< 5")
          

          或者

          replace(A, startsWith("[0-4]", A), "< 5")
          

          结果

          #      [,1]  [,2]         
          # [1,] "< 5" "< 5"        
          # [2,] "< 5" "5 (2.5-7.5)"
          # [3,] "< 5" "7 (5-9)"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-10-23
            • 2015-04-24
            • 1970-01-01
            • 2013-03-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多