[英]Convert factor value into numeric in a column of dataframe
我有一個數據框,每行存儲兩個字符串字符
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
或者使用帶有sub
base R
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
我們可以使用tidyr
extract
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
然后,您可以刪除不需要的列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.