str_replace a defined number of spaces followed by a dot

Viewed 118

I have recently received hundreds of CSV files with many columns. I am facing problems with one of the columns, p.value. This column has values like 1.88737914186277e-14 ., where the actual number is followed by exactly 6 spaces and then a dot. I want to replace all these within my dplyr pipe. How can I do this?

I have tried, for example, df %>% dplyr::mutate(p.value=str_replace(p.value, "[ .]", "")) but obviously is not working. Any help will be appreciated. Thanks.

2 Answers

Try using this pattern: "\\s+\\.$". It detects one or more spaces (\\s+) and a dot right at the end of the string (\\.$)

 df %>% 
   dplyr::mutate(p.value = str_replace(p.value, pattern = "\\s+\\.$", ""))

Since p-values are more useful as numbers I would recommend using readr::parse_number which automatically recognizes and converts string digits:

library(tidyverse)

df %>% mutate(p.value = parse_number(p.value))
Related