Change TRUE and FALSE to Yes and No

橙三吉。 提交于 2019-12-30 11:01:09

问题


I have the following R script:

x <- c('PE', 'MG', 'SP', 'GO', 'ES', 'PB', 'DF')
y <- c('PB', 'MG', 'SP', 'GO', 'ES', 'SE', 'DF')
z <- x == y

So that

> z
[1] FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE

However, I want z (and other logical variables further down the script) to show "Yes" and "No" instead, so I do this recoding:

z <- ifelse(z == TRUE, "Yes", "No")

Is there any way to skip this extra step, i.e., define z show "Yes" instead of "TRUE" and "No" instead of "FALSE".

Of course, I could also do z <- ifelse(x == y, "Yes", "No"), but I'm still looking for something like a parameter inside the options() function I could define just once and have it work until the end of the script (or until I redefined the parameter). Couldn't find anything like it on ?options.


回答1:


As far as I know there is no way to overwrite the fact that R prints TRUE and FALSE for logical objects (personally I think that's good).

The closest solution to what you're looking for could be factor conversion:

z <- factor(x==y, labels=c("No", "Yes"))

> z
[1] No  Yes Yes Yes Yes No  Yes
Levels: No Yes



回答2:


Another approach:

c('No', 'Yes')[z + 1]


来源:https://stackoverflow.com/questions/18642894/change-true-and-false-to-yes-and-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!