r - Conditional assignment of value - is ifelse() the best when condition and intended return value don't have same features? [R]
问题描述
I want to conditionally assign a value to a variable. For example, I want to create an alphabet
variable and assign to it letters
if a certain letter is lowercase, or assign to it LETTERS
if a certain letter is uppercase.
The first thought was to use <-
and ifelse()
. However, this is not working in my case:
> alphabet <- ifelse("B" %in% letters, letters, LETTERS)
> alphabet
[1] "A"
In fact I saw that, with reference to ifelse(test, yes, no)
, the function description says: "ifelse
returns a value with the same shape as test
which is filled with elements selected from either yes
or no
[...]". In the Value section, it specifies a bit more: "A vector of the same length and attributes (including dimensions and "class
") as test
and data values from the values of yes
or no
. [...]".
Ok - I realised that I can use assign()
instead of <-
and the value is assigned correctly to the variable:
> ifelse("B" %in% letters, assign("alphabet", letters), assign("alphabet", LETTERS))
[1] "A"
> alphabet
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
However, as per the output above, ifelse()
still returns the first character from the chosen set of letters.
I am not happy with this, because...
- ... the fact that my code is returning something that I don't need, and...
- ... the fact that
ifelse()
wouldn't actually even work with<-
...
make me wonder whether there is a better way to do this.
Is there a preferred / more efficient / better-etiquette or in any way more appropriate option to assign a value conditionally as in this case, or should I just ignore what is bothering me?
解决方案
我们可以使用if/else
而不是ifelse
alphabet <- if('B' %in% letters) letters else LETTERS
推荐阅读
- python - 当第二个矩阵只有一列时,矩阵乘法会引发错误
- php - 查找 IF 语句的哪个 $_POST 变量为空
- python - 检查字符串中的字符是否与列表的索引范围匹配?
- php - 如何通过ajax重命名下载的文件
- c - 我不知道如何让我的程序读取文件
- angularjs - 如何在 AngularJs 常量中使用全局常量
- html - 如果单击更改按钮,为什么背景颜色没有改变?
- python - 加速 Ising-/Potts-Model Monte-Carlo 的 Python/Numpy 代码
- machine-learning - 使用 20000 个样本进行 MLPClassifier 模型精度微调
- tree - 接受二叉树并返回总和的函数