Nick
Nick

Reputation: 437

Convert from string to Boolean in Julia

I would like to convert an array of strings of "Yes"/"No" to boolean type.

At first, I checked if there were NAs present: convert(Array, datsub[:s734y]) which didn't work, so there were NAs So I converted the NAs to "No" datsub[isna(datsub[:s734y]),:s734y] = "No"

and then this worked: map(s->s==""||s=="NA" ? "No" : s, datsub[:s734y]) so I am somewhat sure (also from viewing the dataset) that I only have "yes"/"no" values

My code to convert it to Boolean is: convert(Vector{Bool}, map(q-> tryparse(Bool, q), datsub[:s734y])) Which returns Inexact Error

Any idea why my code is wrong?

Addendum: type conversion is a general frustration for me at this point.

Upvotes: 3

Views: 3888

Answers (2)

Randy Zwitch
Randy Zwitch

Reputation: 2064

It's hard to follow what you are doing without a reproducible example, but you can do something like the following:

julia> q = ["yes", "no"]

julia> parsebool(s::String) = lowercase(s) == "yes" ? true: false

julia> qbool = Bool[parsebool(x) for x in q]
2-element Array{Bool,1}:
true
false

While slightly more work than using a built-in function, you can also define custom logic for every type of value you encounter as a string. I used the ternary operator, so I'm assuming you just had "yes"/"no". But this example could be easily extended for any series of string values you might accept using if/elseif/else.

Upvotes: 9

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10990

Randy's answer is great for something powerful and robust (e.g. that can handle upper and/or lower case values). For something quick and dirty that will work as long as you have a "clean" array to start with (e.g. no issues with capitalization, etc.) you can just use this:

Array1 = ["Yes", "Yes", "No", "No", "Yes"];
Array2 = Array1 .== "Yes"   

5-element BitArray{1}:
  true
  true
 false
 false
  true

the .== does an element-wise logical comparison of each element in Array1 to see if it equals "Yes".

Note: if you really want Bools, rather than a BitArray, as this gives, then you can use:

Array2 = convert(Array{Bool}, Array1 .== "Yes")

In many cases, Bool and BitArray are largely interchangeable and function quite similarly. For some info on the differences and similarities between these types, see (What's the difference between Array{Bool} and BitArray in Julia and how are they related?)

Upvotes: 6

Related Questions