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, ]
.
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).
CodePudding user response:
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