Reputation: 1704
I have a vector with three levels, which are "M", "S", and "unknown"
I want to change them to numeric (integer) values like this:
If "M" then value 2 (integer)
if "S" then value 1 (integer)
if "unknown" then 0 (integer)
I was going to change them one by one like this:
cards$MaritalStatus[cards$MartialStatus == "M"] <- 2
However, I got exception:
Warning message:
In `[<-.factor`(`*tmp*`, cards$MartialStatus == "M", value = c(1L, :
invalid factor level, NA generated
Any help please?
Upvotes: 2
Views: 177
Reputation: 9656
Here is a more general approach (and maybe easier to understand):
1st - declare values and what they should be changed to.
namesList <- list(M=2, A=1, unknown=0)
2nd - apply changes
unlist(namesList[as.character(cards$MaritalStatus)])
Upvotes: 0
Reputation: 887118
Try
v1 <- factor(c("M","S","unknown","M","S"))
keyval <- setNames(0:2, c('unknown', 'S', 'M'))
as.numeric(keyval[as.character(v1)])
#[1] 2 1 0 2 1
Or
as.numeric(as.character(factor(v1, levels=c('M', 'S', 'unknown'),
labels=c(2,1,0)) ))
#[1] 2 1 0 2 1
Upvotes: 2
Reputation: 34441
I wouldn't take this approach if you had more than 3 values but in this case you could use a nested ifelse statement like so:
ifelse(cards$MaritalStatus=="unknown", 0, ifelse(cards$MaritalStatus=="M", 2, 1))
Upvotes: 1
Reputation: 78600
I would do this with match:
match(cards$MaritalStatus, c("unknown", "S", "M")) - 1
Upvotes: 4