【问题标题】:Convert factor value into numeric in a column of dataframe将因子值转换为数据框列中的数字
【发布时间】:2020-02-15 21:51:47
【问题描述】:

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

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


【解决方案1】:

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

【讨论】:

  • 显示错误:parse_vector(x, col_number(), na = na, locale = locale, trim_ws = trim_ws) 错误:is.character(x) 不正确
  • @shome 我以为是character。更新为as.character
【解决方案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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 2014-01-05
      • 2014-06-15
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多