user13467695
user13467695

Reputation:

How to remove part of string value in column using stringr library?

I have a dataframe with a column:

value-1245
value-4578
value-9976

I want to remove "value-" from it and turn it into numeric. So desired result is:

1245
4578
9976

How to do that? I tried str_replace(column1, "value-", "") but it doesn't work.

Upvotes: 1

Views: 2600

Answers (3)

TarJae
TarJae

Reputation: 79246

We could use extract_numeric function from tidyr package and combine witth abs to remove the minus sign:

library(tidyr)
df %>%
    mutate(column1 = abs(extract_numeric(column1)))

Output:

  column1
1    1245
2    4578
3    9976

data:

df <- data.frame(column1 = c("value-1245", "value-4578","value-9976"))

Upvotes: 1

akrun
akrun

Reputation: 887891

We could use trimws in base R

as.numeric(trimws(df$column1, whitespace = "value-"))

Or with readr::parse_number

readr::parse_number(df$column1)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389275

You can use str_remove which is shortcut for str_replace with empty replacement ("")

as.numeric(stringr::str_remove(df$column1, "value-"))

Or in base R -

as.numeric(sub("value-", "", df$column1))

Upvotes: 1

Related Questions