简体   繁体   English

如何用 R 中的另一个词替换向量中的所有是或否?

[英]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.

相关问题 如何将特定单词替换为 R 中的另一个单词 - how to replace a specific word into another word in R 在 R 中,如何使用返回可能输出向量的歧义的所有选项替换字符串中的歧义字符? - In R, How can I replace ambiguous characters in string with all options for the ambiguity returning a vector of possible outputs? 如何在 R 的向量中查找和替换特定的数字序列? - How can I find and replace a specific sequence of numbers in a vector in R? 如何在R中以固定间隔替换序列中的向量值? - How can I replace vector values in a sequence at regular intervals in R? 如何在R中将向量中的所有负值替换为0 - How to replace all negative values in vector by 0 in R R中另一个向量中存在匹配值时,如何替换向量中的值? - How do I replace values in a vector when matching values exist in another vector in R? 如何用R中另一个向量的相同索引替换向量的某些索引? - How to replace some indices of a vector with the same indices of another vector in R? R如何用数据表中的另一个值向量替换/gsub一个值向量 - R how to replace/gsub a vector of values by another vector of values in a datatable 我们如何替换R中向量中的元素? - How can we replace elements in a vector in R? 如何获得R中矢量的所有可能分区的列表? - How can I get a list of all possible partitions of a vector in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM