[英]How can I replace all the yes or nos in a vector with another word in R?
I have a vector whose only entries are yes or no.我有一个向量,其唯一的条目是是或否。 I need to replace each yes with "Institutional" and every no with "Retail".
我需要用“机构”替换每个“是”,用“零售”替换每个“否”。
I have tried for loops, ifelse statements, case_when and replace functions, all to no avail.我尝试过 for 循环、ifelse 语句、case_when 和 replace 函数,但都无济于事。 They all still return the same vector full of yes and no.
他们都仍然返回相同的向量,充满了是和否。
I would suggest this:我建议这样做:
#Data
vec <- rep(c('yes','no'),10)
vec
[1] "yes" "no" "yes" "no" "yes" "no" "yes" "no" "yes" "no" "yes" "no" "yes" "no" "yes" "no" "yes"
[18] "no" "yes" "no"
#Replace
vec[vec=='yes'] <- 'Institutional'
vec[vec=='no'] <- 'Retail'
vec
[1] "Institutional" "Retail" "Institutional" "Retail" "Institutional" "Retail"
[7] "Institutional" "Retail" "Institutional" "Retail" "Institutional" "Retail"
[13] "Institutional" "Retail" "Institutional" "Retail" "Institutional" "Retail"
[19] "Institutional" "Retail"
Maybe you can try ifelse
like below也许你可以试试
ifelse
像下面
v <- ifelse(v == "yes","Institutional","Retail")
or play some tricks with factor
或玩一些花样的
factor
v <- as.character(factor(v,levels=c("no","yes"), labels = c("Retail","Institutional")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.