shome
shome

Reputation: 1402

Convert factor value into numeric in a column of dataframe

I have a data frame that has two string characters stored in each row

s   ['64.0', '2']   
a   ['63.0', '2']   
b   ['63.0', '1']   

How to convert the first character string into numeric value,and omit the second character string,which results into data frame as follows :

s    64.0   
a    63.0
b    63.0   

Upvotes: 0

Views: 87

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 389235

We can use extract from tidyr

tidyr::extract(df, col2, into = c('col2', 'col3'), "(\\d+\\.\\d+).*(\\d)")

#  col1 col2 col3
#1    s 64.0    2
#2    a 63.0    2
#3    b 63.0    1

You can then remove the columns which you don't need.

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

Here is another base R solution using regmatches, i.e.,

df <- within(df, col2 <- as.numeric(sapply(regmatches(col2,gregexpr("[0-9\\.]+",col2)),`[[`,1)))

such that

> df
  col1 col2
1    s   64
2    a   63
3    b   63

Upvotes: 1

akrun
akrun

Reputation: 887841

We could use parse_number

library(dplyr)
library(readr)
df2 <-  df1 %>%
          mutate(col2 = parse_number(as.character(col2)))
df2
#   col1 col2
#1    s   64
#2    a   63
#3    b   63

Or using base R with sub

as.numeric( sub("\\D+([0-9.]+)[^0-9]+.*", "\\1", df1$col2))

data

df1 <- structure(list(col1 = c("s", "a", "b"), col2 = structure(3:1, .Label = c("['63.0', '1']", 
"['63.0', '2']", "['64.0', '2']"), class = "factor")), row.names = c(NA, 
-3L), class = "data.frame")

Upvotes: 3

Related Questions