Skip to content
This repository has been archived by the owner on Sep 10, 2023. It is now read-only.

Replace ifelse #41

Merged
merged 1 commit into from
Dec 31, 2020
Merged

Replace ifelse #41

merged 1 commit into from
Dec 31, 2020

Conversation

rikhuijzer
Copy link
Contributor

When using the code, I noticed that ifelse is used. This function also exists in R, and for me one of the main reasons I try to avoid R. In R, it's just a hack to get stuff done because the language isn't very expressive, and because everything has to be vectorized. Luckily, we're using Julia here, so we can use clearer syntax! 😄

In this PR, I propose to change all occurrences of ifelse with list comprehensions.

Example

Say, we want to replace "a" with 1, and "b" with 2 in A:

julia> A = ["a", "b", "a"]
3-element Array{String,1}:
 "a"
 "b"
 "a"

We could write

julia> map(x -> ifelse(x == "a", 1, 2), A)
3-element Array{Int64,1}:
 1
 2
 1

However, it is more common (and, I think, more readable) to use a ternary expression (like in C) in combination with a list comprehension

julia> [x == "a" ? 1 : 2 for x in A]
3-element Array{Int64,1}:
 1
 2
 1

@goedman goedman merged commit 44bd1e3 into StatisticalRethinkingJulia:master Dec 31, 2020
@goedman
Copy link
Member

goedman commented Dec 31, 2020

Thanks Rik!

@rikhuijzer
Copy link
Contributor Author

👍

@rikhuijzer rikhuijzer mentioned this pull request Dec 31, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants