Replace all occurrences of a string in a data frame

后端 未结 6 685
面向向阳花
面向向阳花 2020-11-27 02:54

I\'m working on a data frame that has non-detects which are coded with \'<\'. Sometimes there is a space after the \'<\' and sometimes not e.g. \'<2\' or \'< 2\

6条回答
  •  一整个雨季
    2020-11-27 03:15

    Here is a dplyr solution

    library(dplyr)
    library(stringr)
    
    Censor_consistently <-  function(x){
      str_replace(x, '^\\s*([<>])\\s*(\\d+)', '\\1\\2')
    }
    
    
    test_df <- tibble(x = c('0.001', '<0.002', ' < 0.003', ' >  100'),  y = 4:1)
    
    mutate_all(test_df, funs(Censor_consistently))
    
    # A tibble: 4 × 2
    x     y
     
    1  0.001     4
    2 <0.002     3
    3 <0.003     2
    4   >100     1
    

提交回复
热议问题