1

I have strings like "<x" which must be changed to "x".

for example:

"<0.1" will be "0.1"

I tried this:

data2[1:nrow(data2),] <- as.data.frame(apply(data2[1:nrow(data2),], 2, function(x) sub("<a*", "", x)))

But it also changes strings like "wrong (<0.1)" to "wrong (0.1)". It has to only change the values like "<x" to "x".

I searched for examples like: String replace specific part of string Replace $x<y$ by $x < y$

But they unfortunately did not help.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Quinten
  • 35,235
  • 5
  • 20
  • 53
  • have a look to [https://stackoverflow.com/questions/23983450/how-to-replace-strings-containing-greater-than-and-less-than]. Special characters need to be dealt specifically (sometimes escaped multiple times). – splaisan Feb 08 '21 at 10:04
  • 1
    like this? `sub("^ – Sandipan Dey Feb 08 '21 at 10:37

1 Answers1

1

You can use readr's parse_number function to extract the number from text directly.

library(dplyr)
library(readr)

df <- data.frame(a = c('1', '>0.01', '<0.2'), b = c(1, 'wrong (<0.1)', '<0.05'))

df %>% mutate(across(.fns = parse_number))
#     a    b
#1 1.00 1.00
#2 0.01 0.10
#3 0.20 0.05
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • It works for <0.1 to 0.1, but how do you change "wrong (<0.1)" to "0.1"? 0.1 could be any number – Quinten Feb 08 '21 at 11:27
  • But you said you don't want to change that? Using `dplyr` and `readr` try `df %>% mutate(across(.fns = parse_number))` – Ronak Shah Feb 08 '21 at 11:29
  • I said that it also changes "wrong (<0.1)" to "wrong (0.1)", which is not good because I only want the numbers. It only removed < and not all text except the numbers. – Quinten Feb 08 '21 at 11:32
  • I tried this: `str_replace_all(x, "[wrong(<)]", "")` and worked also – Quinten Feb 08 '21 at 12:15