1

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.

1

3 Answers 3

1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

and how to do it in pipeline? cause when I use it in pipeline, it says that object column1 not found. I use it as %>% as.numeric(stringr::str_remove(column1, "value-"))
If your dataframe is called df and column as column1 you can do - df %>% mutate(column1 = as.numeric(stringr::str_remove(column1, "value-")))
1

We could use trimws in base R

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

Or with readr::parse_number

readr::parse_number(df$column1)

Comments

1

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"))

Comments