GregdeLima
GregdeLima

Reputation: 404

How to continue to use factor where one level is missing (has been removed)?

I'm working with a set of Fitbit data that I've downloaded and it has a list of weekdays that I'm trying to order properly. Now, the current data set has no "Fridays", but I want the factors to include it regardless.

How can I continue to factor the Weekdays, as 1-7 even if there are only 6 weekdays in the data set?

file<-choose.files()
   slp<-data.frame(read.csv(file))

   wkdaylevels<-c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

    slp$FellAsleepAt<-strptime(slp$FellAsleepAt, format="%B %e, %Y at %I:%M%p")
    slp$AwokeAt<-strptime(slp$AwokeAt,format="%B %e, %Y at %I:%M%p")
    slp$TotalTimeSlept<-gsub("h ",":",slp$TotalTimeSlept)
    slp$TotalTimeSlept<-gsub("m","",slp$TotalTimeSlept)
    slp$TimeAsleep<-as.numeric(difftime(slp$AwokeAt,slp$FellAsleepAt))
    slp$Date<-as.Date(slp$FellAsleepAt, format="%M/%D/%Y")
    slp$DayofWeek<-as.factor(weekdays(slp$Date),levels=wkdaylevels)



    ggplot(slp,aes(x=DayofWeek,y=TimeAsleep))+
        geom_point()

Data here: https://docs.google.com/spreadsheets/d/1Vdgmtwx0vNKDKEZFMEGAWQ58H66ia-xjI0evR7idfkc/edit?usp=sharing

Upvotes: 0

Views: 5287

Answers (2)

alexwhitworth
alexwhitworth

Reputation: 4907

Answer: Use factor not as.factor

The function as coerces an object to a class. In your case, as.<type> coerces to a type (factor for you). The function factor is used to encode an object as a factor. The key difference is that as.factor does not allow a levels parameter, whereas factor does.

If you examine the source code of each function, you will see that as.factor does the coercion by using the unique levels of the object as its levels. factor does this if the levels= parameter is not specified, but allows the input of levels.

For example:

x <- 1:6
x2 <- factor(x, levels= 1:7)
levels(x2)
[1] "1" "2" "3" "4" "5" "6" "7"
x2 <- as.factor(x, levels= 1:7) # in this case, levels won't be evaluated due to lazy evaluation
Error in as.factor(x, levels = 1:7) : unused argument (levels = 1:7)

TBH, I'm not sure why your R session isn't giving you this error. Are you using R 3.2.3?

Upvotes: 5

lukeA
lukeA

Reputation: 54237

Use levels<- (?levels for help):

wdays <- as.factor(c("Sunday", "Monday"))
wkdaylevels<-c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
levels(wdays) <- wkdaylevels
wdays
# [1] Monday Sunday
# Levels: Sunday Monday Tuesday Wednesday Thursday Friday Saturday

And if you want to drop unused levels, you can use

droplevels(wdays)
# [1] Monday Sunday
# Levels: Sunday Monday

or

factor(wdays)
# [1] Monday Sunday
# Levels: Sunday Monday

Upvotes: 2

Related Questions