TMOTTM
TMOTTM

Reputation: 3381

How can I assign a custom factor depending on another column?

I have data like this:

k <- data.frame(v=c(1:4),
                days=c("m", "m", "s", "m"),
                weekend=c(F, F, T, F)
     )

Lets say m is monday and s is saturday, so s rows are weekends.

How can I create a factor variable weekendfactor such that

> k
  v days   end weekendfactor
1 1    m FALSE       Weekday
2 2    m FALSE       Weekday
3 3    s  TRUE       Weekend
4 4    m FALSE       Weekday

I guess it somehow involves the gl function but I cant get my head around it (my mind is working in if statements).

Upvotes: 0

Views: 64

Answers (3)

akrun
akrun

Reputation: 887048

Or,

as.character(factor(k$days, labels=c("Weekday", "Weekend")))
#[1] "Weekday" "Weekday" "Weekend" "Weekday"

Upvotes: 1

David Arenburg
David Arenburg

Reputation: 92282

Another way (as I hate ifelse) will be

c("Weekday", "Weekend")[k$weekend + 1]
# [1] "Weekday" "Weekday" "Weekend" "Weekday"

Upvotes: 2

Thomas
Thomas

Reputation: 44525

Code:

library("car")
recode(k$days, "'m'='Weekday';'s'='Weekend'")

Result:

> k
  v days weekend weekendFactor
1 1    m   FALSE       Weekday
2 2    m   FALSE       Weekday
3 3    s    TRUE       Weekend
4 4    m   FALSE       Weekday

Since you already have your weekend column, you could also do:

ifelse(k$weekend, "Weekend", "Weekday")

To produce the same result (except that it will be "character" not "factor" class).

Upvotes: 2

Related Questions