Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subset dataframe after addNA of an factor

I’ve got a dataframe with a continuous variable x and a grouping factor. I need to add NA as a factor level for some reason. As a result, the data is:

df <- data.frame(x= 1:4, group= factor(c(NA, 1, 1, 2)))
df$group <- addNA(df$group)

How can I now subset the data in the "group" variable for the NA values? I attempted:

df[df$group == "NA", ]
df[df$group == "<NA>", ]
df[is.na(df$group), ]
df[df$group == levels(df$group)[3], ]

My expected output contains all rows where df$group has factor level NA, i.e. data.frame(x= 1:4, group= factor(c(NA, 1, 1, 2)))[1, ].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I do need to add NA as factor level since it is pretty handy in my situation (see here for one case where it is useful).

>Solution :

You can try this approach:

df[is.na(as.character(df$group)),]
  x group
  1  <NA>

moving the variable to character before looking for na values

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading