Reputation: 83
I would like to convert a character variable into a factor matching part of string. For example I have this kind of output
c("09:32", "09:55" ,"09:51", "09:52", "08:36", "08:44", "08:21" ,"08:00")
and I want to create a factor with two levels splitting times for hours. Could you help me?
Upvotes: 1
Views: 543
Reputation: 5586
This can be accomplished even more simply than in the other answer. If x
is your vector of strings, just do this:
factor(substring(x, 1, 2))
This creates a factor variable where the levels are the first two characters in x
.
P.S. Thanks to David Arenburg for posting this in a comment and giving me permission to post as an answer!
Upvotes: 1
Reputation: 2000
x <- c("09:32", "09:55", "09:51")
hour <- factor(as.numeric(substring(x, 1, 2)), levels = c(8, 9))
Upvotes: 0