Sebastiano Caliò
Sebastiano Caliò

Reputation: 83

Convert character to factor matching part of string

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

Answers (2)

Alex A.
Alex A.

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

Michele Usuelli
Michele Usuelli

Reputation: 2000

x <- c("09:32", "09:55", "09:51")
hour <- factor(as.numeric(substring(x, 1, 2)), levels = c(8, 9))

Upvotes: 0

Related Questions