How to subset data in R without losing NA rows?

后端 未结 3 1555
無奈伤痛
無奈伤痛 2020-11-29 10:38

I have some data that I am looking at in R. One particular column, titled \"Height\", contains a few rows of NA.

I am looking to subset my data-frame so that all He

3条回答
  •  無奈伤痛
    2020-11-29 11:27

    For subsetting by character/factor variables, you can use %in% to keep NAs. Specify the data you wish to exclude.

    # Create Dataset
    library(data.table)
    df=data.table(V1=c('Surface','Bottom',NA),V2=1:3)
    df
    #         V1 V2
    # 1: Surface  1
    # 2:  Bottom  2
    # 3:      3
    
    # Keep all but 'Bottom'
    df[!V1 %in% c('Bottom')]
    #         V1 V2
    # 1: Surface  1
    # 2:      3
    

    This works because %in% never returns an NA (see ?match)

提交回复
热议问题