将数据框列中的因子值转换为数字

Convert factor value into numeric in a column of dataframe

我有一个数据框,每行存储了两个字符串字符

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

如何将第一个字符串转换成数值,省略第二个字符串,结果成data frame如下:

s    64.0   
a    63.0
b    63.0   

我们可以使用 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

或使用 base Rsub

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

数据

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

这是另一个使用 regmatches 的基本 R 解决方案,即

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

这样

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

我们可以使用 extracttidyr

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

然后您可以删除不需要的列。