问题
s ['64.0', '2']
a ['63.0', '2']
b ['63.0', '1']
How to convert it into data frame as follows :
s 64.0
a 63.0
b 63.0
回答1:
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")
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/60243453/convert-factor-value-into-numeric-in-a-column-of-dataframe