【问题标题】:Converting "-" to a "0" in R [duplicate]在R中将“-”转换为“0”[重复]
【发布时间】:2019-05-16 03:45:58
【问题描述】:

我在数据框dframe 中有一个列Apps

看起来像这样:

    Apps
1    31
2    12
3    10
4    33
5    -

我需要将列输入 int 而不是 String,所以我需要将第 5 行转换为 0。

    Apps
1    31
2    12
3    10
4    33
5    0

【问题讨论】:

  • 你是如何将这些数据读入 R 的?使用read.table(..., na.strings="-") 从一开始就将其读取为缺失可能是个好主意。
  • dframe$Apps[ dframe$Apps == "-" ] <- "0"?不过,我同意 MrFlick 的观点,因为“0”的值与连字符不同,许多程序(不是 R)将连字符解释为“无效数字”。我猜现在是character。使用na.strings= 参数,第一次正确读取它并让read.table 为您处理列类是非常值得的。它并不完美,但其他任何事情都表明您的数据存在其他问题。 (顺便说一句:dframe$Apps <- as.numeric(dframe$Apps) 对你来说可能就足够了。)

标签: r


【解决方案1】:
dframe$Apps <- as.integer(gsub("-", "0", dframe$Apps, fixed = TRUE))

我怀疑你想要一个整数列。

【讨论】:

    【解决方案2】:

    您可以使用ifelsetidyverse 方法来做到这一点:

    require(tidyverse)
    
    df %>% 
      mutate(Apps = ifelse(Apps == "-", 0, Apps))
    
      Apps
    1    4
    2    3
    3    2
    4    5
    5    0
    

    数据集:

    df <- read.table(text = "    Apps
    1    31
    2    12
    3    10
    4    33
    5    -", header = TRUE)
    

    【讨论】:

      【解决方案3】:
      dframe$Apps[dframe$Apps == "-"] <- "0"
      dframe$Apps <- as.integer(dframe$Apps)
      

      【讨论】:

        猜你喜欢
        • 2017-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        • 1970-01-01
        • 2018-03-07
        • 2019-02-28
        • 2020-11-19
        相关资源
        最近更新 更多