Replace all 0 values to NA

前端 未结 8 2593
庸人自扰
庸人自扰 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:18

    You can replace 0 with NA only in numeric fields (i.e. excluding things like factors), but it works on a column-by-column basis:

    col[col == 0 & is.numeric(col)] <- NA
    

    With a function, you can apply this to your whole data frame:

    changetoNA <- function(colnum,df) {
        col <- df[,colnum]
        if (is.numeric(col)) {  #edit: verifying column is numeric
            col[col == -1 & is.numeric(col)] <- NA
        }
        return(col)
    }
    df <- data.frame(sapply(1:5, changetoNA, df))
    

    Although you could replace the 1:5 with the number of columns in your data frame, or with 1:ncol(df).

提交回复
热议问题