user3115933
user3115933

Reputation: 4443

How to extract numbers from a column in a data frame and add them in a new column

I have a dataframe named df and it has one column (Today's price) as string values.

Here is an extract of that column:

Today's price
MUR 15,265
MUR 20,000
MUR  9,841

I need a new column in my dataframe (df) called "Price" (extracted from "Today's price" column) as follows:

Price
15265
20000
 9841

Here is what I did and I am getting "NA" for all records and it is not creating the "Price" column.

df %>% 
  mutate(Price = as.integer(str_extract("Today's price", "[0-9]+")))

I am using the dplyr and stringr libraries.

Where am I going wrong?

Upvotes: 2

Views: 1679

Answers (1)

TarJae
TarJae

Reputation: 78917

We could use parse_number

library(dplyr)
library(readr)
df %>% 
  mutate(Price = parse_number(`Today's price`)) %>% 
  select(-`Today's price`)

Even shorter with:

df %>% 
  mutate(Price = parse_number(`Today's price`), .keep = "unused")

Output:

 Price
  <dbl>
1 15265
2 20000
3  9841

Upvotes: 3

Related Questions