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

问题描述 投票:-2回答:3
s   ['64.0', '2']   
a   ['63.0', '2']   
b   ['63.0', '1']   

如何如下将其转换为数据框:

s    64.0   
a    63.0
b    63.0   
r dataframe character numeric
3个回答
3
投票

我们可以使用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 R一起使用sub

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

2
投票

这里是另一种使用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

1
投票

我们可以使用extract中的tidyr

© www.soinside.com 2019 - 2024. All rights reserved.