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?
我会用匹配来做到这一点:
match(cards$MaritalStatus, c("unknown", "S", "M")) - 1
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
如果你有超过3个值,我不会采用这种方法但在这种情况下你可以使用嵌套的ifelse语句,如下所示:
ifelse(cards$MaritalStatus=="unknown", 0, ifelse(cards$MaritalStatus=="M", 2, 1))
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)])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.