Replace all 0 values to NA

前端 未结 8 2220
庸人自扰
庸人自扰 2020-11-22 08:48

I have a dataframe with some numeric columns. Some row has a 0 value which should be considered as null in statistical analysis. What is the fastest way to replace all the 0

8条回答
  •  醉酒成梦
    2020-11-22 09:17

    dplyr::na_if() is an option:

    library(dplyr)  
    
    df <- data_frame(col1 = c(1, 2, 3, 0),
                     col2 = c(0, 2, 3, 4),
                     col3 = c(1, 0, 3, 0),
                     col4 = c('a', 'b', 'c', 'd'))
    
    na_if(df, 0)
    # A tibble: 4 x 4
       col1  col2  col3 col4 
         
    1     1    NA     1 a    
    2     2     2    NA b    
    3     3     3     3 c    
    4    NA     4    NA d
    

提交回复
热议问题