s ['64.0', '2']
a ['63.0', '2']
b ['63.0', '1']
如何如下将其转换为数据框:
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 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")
这里是另一种使用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
我们可以使用extract
中的tidyr