bvowe
bvowe

Reputation: 3384

Remove custom character string and convert scientific notation

Sample

    data=data.frame("first"=c("A","B","C"),
"one"=c(1:3),
                    "two"=c("2.1e-003*", 5, "1.9e-9*"),
                            "three"=c("1.6e-002*", 5, "8.1e-2*"))

My aim is to remove "*" and convert science notation to numeric.

I tried to no avail

WANT=gsub("\\*.*","",data)

Upvotes: 1

Views: 222

Answers (1)

dipetkov
dipetkov

Reputation: 3700

library("tidyverse")

data <- data.frame(
  "first" = c("A", "B", "C"),
  "one" = c(1:3),
  "two" = c("2.1e-003*", 5, "1.9e-9*"),
  "three" = c("1.6e-002*", 5, "8.1e-2*")
)

data %>%
  # Cast unhelpful `factor` columns to `character`
  mutate_at(vars(two, three), as.character) %>%
  mutate_at(vars(two, three), parse_number) %>%
  # You can turn off the scientific notation
  # but you end up with a lot of zeros...
  mutate_at(vars(two, three), format, scientific=FALSE)
#>   first one          two three
#> 1     A   1 0.0021000000 0.016
#> 2     B   2 5.0000000000 5.000
#> 3     C   3 0.0000000019 0.081

Created on 2019-03-29 by the reprex package (v0.2.1)

Upvotes: 2

Related Questions