【问题标题】:Is there a function any function that convert character to double in R是否有任何函数可以在 R 中将字符转换为双精度
【发布时间】:2022-11-23 01:47:06
【问题描述】:

是否有任何函数可以将诸如“1,8”之类的东西转换为 1.8

我尝试 as.double 但它似乎不起作用。

我需要转换数据框的一列(只有像“1,3”这样的字符)。而且我不明白为什么,当我使用 as.double 时,我只有 Nas

【问题讨论】:

    标签: r converters


    【解决方案1】:

    就在这里!使用 readr 包中的 parse_number

    library(readr)
    numbers <- c("1,8", "1,3")
    parse_number(numbers, locale = locale(decimal_mark = ","))
    # [1] 1.8 1.3
    

    或者,如果您更喜欢使用 R 基本函数,则可能需要使用 sub, 替换为 .,然后应用 as.numeric

    as.numeric(sub(",", ".", numbers))
    # [1] 1.8 1.3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2020-12-15
      相关资源
      最近更新 更多