【问题标题】:as.numeric creates NA when there are blank spacesas.numeric 在有空格时创建 NA
【发布时间】:2020-02-20 03:15:27
【问题描述】:

当使用mutate_at 将数据中的变量更改为字符、数字或因子时,我遇到了数字变量的问题:

library(dplyr)

f <- c('V1', 'V2')
c <- c('V3', 'V4')
n <- c('V5', 'V6')

data <- data.frame(V1 = c(0,2,""),
                   V2 = c("", 3, 4),
                   V3 = c(1, 2, 3),
                   V4 = c(0, 0, ""),
                   V5 = c(-1, -1, ""),
                   V6 = c(0, 1, ""))

data <- data %>% 
        mutate_at(f, as.factor) %>%
        mutate_at(c, as.character) %>%
        mutate_at(n, as.numeric)

在这种特定情况下,我得到了一些奇怪的结果:

    V1 V2 V3 V4 V5 V6
  1  0     1  0  2  2
  2  1  3  2  0  2  3
  3     4  3     1  1

在其他情况下,如在我的原始数据中,我用NA 代替空格。

有人可以帮忙吗?

【问题讨论】:

  • 在管道开头添加mutate_all(as.character)

标签: r na dplyr


【解决方案1】:

使用readr::parse_guess 进行合适的转换怎么样?

library(dplyr)
library(readr)
data %>% mutate_all(~parse_guess(as.character(.x)))
#  V1 V2 V3 V4 V5 V6
#1  0 NA  1  0 -1  0
#2  2  3  2  0 -1  1
#3 NA  4  3 NA NA NA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多