na.strings applied to a dataframe

前端 未结 4 560
無奈伤痛
無奈伤痛 2021-01-18 07:41

I currently have a dataframe in which there are several rows I would like converted to \"NA\". When I first imported this dataframe from a .csv, I could use na.strings=c(\"A

4条回答
  •  情深已故
    2021-01-18 08:17

    Here's a way to replace values in multiple columns:

    # an example data frame
    dat <- data.frame(x = c("D", "E", "F", "G"), 
                      y = c("A", "B", "C", "D"), 
                      z = c("X", "Y", "Z", "A"))
    #   x y z
    # 1 D A X
    # 2 E B Y
    # 3 F C Z
    # 4 G D A
    
    # values to replace
    na.strings <- c("D", "E", "F")
    
    # index matrix 
    idx <- Reduce("|", lapply(na.strings, "==", dat))
    
    # replace values with NA
    is.na(dat) <- idx
    
    dat
    #     x    y z
    # 1     A X
    # 2     B Y
    # 3     C Z
    # 4    G  A
    

提交回复
热议问题