【问题标题】:ways to remove N/As from the columns in R从 R 中的列中删除 N/As 的方法
【发布时间】:2022-06-30 17:32:46
【问题描述】:

我正在尝试将字符列值转换为数字,以便稍后将一列除以另一列。我得到 N/A 值。我想这可能是因为逗号。我尝试使用以下代码:

    ```r
col1 <- c("L1","L2","L3","L4","L5" )
col2 <- c("910", "458", "34,613" , "201" , "1,886")
col3 <- c("87,282","41,304", "5,146,982", "348,520", "27,274")
df <- data.frame(col1, col2, col3, stringsAsFactors = FALSE)
df$col2 <-as.factor(df$col2)
df$col3 <-as.factor(df$col3)
#Convert chr to numeric
df[,'col2'] <- as.numeric(as.character(df[,'col2']))
#> Warning: NAs introduced by coercion
df[,'col3'] <- as.numeric(as.character(df[,'col3']))
#> Warning: NAs introduced by coercion
#try to get rid of commas
gsub(",", "", df$col3)
#> [1] NA NA NA NA NA
df$new <- df$col3/df$col2
Created on 2022-06-30 by the reprex package (v2.0.1)
**I also tried:**

  

      ``` r
    df[,'col2'] <- as.numeric(as.character(df[,'col2']))
    #> Warning: NAs introduced by coercion
    as.numeric(gsub(",", "", df$col3))
    #> [1] NA NA NA NA NA
    ``` 
    <sup>Created on 2022-06-30 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)</sup>

**I also tried this way, which does not produce N/As, but still has commas:**
    ```
     setClass("num.with.commas")
    setAs("character", "num.with.commas", 
          function(from) as.numeric(gsub(",", "", from) ) )
    colClasses=c('num.with.commas','factor','character','numeric','num.with.commas')
    #it does not remove commas, but it has no N/As
    ```
    Created on 2022-06-30 by the reprex package (v2.0.1)

**And the last effort which produced only errors:**

      ```
     dft %>%
      mutate_all(funs(as.character(.)), col2, col3) %>%
      mutate_all(funs(gsub(",", "", .)), col2, col3) %>%
      mutate_all(funs(as.numeric(.)), col2, col3)
    #> Error in dft %>% mutate_all(funs(as.character(.)), col2, col3) %>% mutate_all(funs(gsub(
    ```

【问题讨论】:

    标签: r na numeric


    【解决方案1】:

    一个可能的解决方案:

    library(tidyverse)
    
    col1 <- c("L1","L2","L3","L4","L5" )
    col2 <- c("910", "458", "34,613" , "201" , "1,886")
    col3 <- c("87,282","41,304", "5,146,982", "348,520", "27,274")
    df <- data.frame(col1, col2, col3)
    
    df %>% 
      mutate(across(-1, ~ str_remove(.x, ","))) %>% 
      type.convert(as.is = T)
    #>   col1  col2     col3
    #> 1   L1   910    87282
    #> 2   L2   458    41304
    #> 3   L3 34613 5146,982
    #> 4   L4   201   348520
    #> 5   L5  1886    27274
    

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 2019-02-04
      • 2018-05-03
      • 1970-01-01
      相关资源
      最近更新 更多