jeudi 29 juillet 2021

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...

  1. ... the fact that my code is returning something that I don't need, and...
  2. ... 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?

Aucun commentaire:

Enregistrer un commentaire