Creating a factor to include NA as a level

62 Views Asked by At

Hi everyone I am working with a pretty large data set that I have converted to a factor my problem is that I need the NAs to be counted as N and be a part of the data set. I successfully changed the data to the factor but cannot for the life of me get NA data to show up under N here is what I have

We need to convert the pell.elig into a factor so that we may utilize the data appropriately

factor(Student_Data$Pell.Elig, exclude = NULL, 
       levels = c("Y", NA), 
       labels = c("Y", "N"))
levels(Student_Data$Pell.Elig)

We will then run a table of first gen and pell eligible to see the results.

table(as.factor(Student_Data$firstgen),Student_Data$Pell.Elig)
      Y   N
  FG 403   0
  OP 133   0
  TP  85   0

My table is showing 0's for N but I need them to be indicative of the NA's.

1

There are 1 best solutions below

0
On BEST ANSWER

We can change the NA elements to "N"

levels(Student_Data$Pell.Elig) <- c("Y", "N")
Student_Data$Pell.Elig[is.na(Student_Data$Pell.Elig)] <- "N"

Or another option is fct_explicit_na

library(forcats)
table(as.factor(Student_Data$firstgen),
      fct_explicit_na(Student_Data$Pell.Elig, na_level = "N"))