代码之家  ›  专栏  ›  技术社区  ›  ip2018

将数据框架中的所有0值用1替换为多行多列

  •  0
  • ip2018  · 技术社区  · 8 年前

    如何将数据帧中的所有NA、NAN、0、0.00、0.000值都替换为1,并同时替换为多行和多列?谢谢。

    示例df:

    a = c(233, 0, NA, 3455)
    b = c(23, 0.000, NA, 345)
    c = c(223, 0.00, NaN, 30055)
    
    df = cbind.data.frame(a,b,c)
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   wibeasley    8 年前

    我喜欢扎克的建议 dplyr::mutate_all() .另一个选择是 purrr::map_df() .

    scrub <- function( x ) {
      x <- dplyr::if_else(dplyr::near(x, 0), 1, x)
      x <- dplyr::coalesce(x, 1)
      x
    }
    
    # Option 1 (These four lines are equivalent):
    df %>%                                  # This needs `library(magrittr)` 
      purrr::map_df(scrub)
    purrr::map_df(df, scrub)
    purrr::map_df(df, ~scrub(.))
    purrr::map_df(df, function(x) scrub(x))
    
    # Option 2, suggested by @zack in the comments:
    dplyr::mutate_all(df, scrub)
    

    这是结果 purr::映射df() ,这是一个 tibble .这个 dplyr::mutate_all()。 返回 data.frame .

    # A tibble: 4 x 3
          a     b     c
      <dbl> <dbl> <dbl>
    1   233    23   223
    2     1     1     1
    3     1     1     1
    4  3455   345 30055