Reputation: 17
Right now I have a column of data that is "blue" or "green" and I want it to display a 1 for "blue" and 0 for "green." Any help?
Upvotes: 1
Views: 148
Reputation: 1706
Evaluations of logical statements can be converted to binary values.
x = c("blue", "green", "blue")
as.integer(x == "blue")
Upvotes: 3
Reputation: 162321
This is a safer approach than several of the others given so far, because it won't silently miscode a value other than "blue"
or "green"
that happens to occur in your input vector x
:
x <- c("blue", "green", "blue", "blue", "red")
match(x, c("green", "blue")) - 1
# [1] 1 0 1 1 NA
Alternatively (and even easier to arbitrarily extend), use the following (h.t. thelatemail):
val <- setNames(c(0,1,10), c("green", "blue", "red"))
x <- c("blue", "green", "blue", "blue", "red", "orange")
val[x]
# blue green blue blue red <NA>
# 1 0 1 1 10 NA
Upvotes: 3
Reputation: 16277
Another way to do it
vec[vec=="blue"] <-1
vec[vec=="green"] <-0
as.numeric(vec)
#[1] 1 0 1 0 1 0
Upvotes: 1
Reputation: 16277
One way to do that (there are several)
vec <-rep(c("blue","green"),3)
ifelse(vec=="blue",1,0)
#[1] 1 0 1 0 1 0
Upvotes: 1