Message Boards Message Boards

Easy way to convert a string into a numeric (real or integer)?

I downloaded air quality monitoring data from open data sites for spatial data analysis and found that the monitoring value type was a string. Is there an easy way to convert a string into a numeric(real or integer)? Besides, monitoring values ??include missing ??and error values. Is there a better way to clean up?

data = Select[#[[3]] != "" && 
        ContainsOnly[
         ToCharacterCode[#[[3]]], {46, 48, 49, 50, 51, 52, 53, 54, 55,
           56, 57}] &]@Values@KeyDrop[#, "PublishTime"] &@
   DeleteDuplicates@
    Query[All, {"Latitude", "Longitude", "PM2.5", "PublishTime"}]@
     Import["https://opendata.epa.gov.tw/ws/Data/AQI/?$format=json", 
      "RawJSON", CharacterEncoding -> "CP950"];
data = Map[{GeoPosition[ToExpression[{#[[1]], #[[2]]}]], #[[3]]} &, 
   data];
Head[#] & /@ data[[All, 2]]
POSTED BY: Tsai Ming-Chou

A naive solution uses ToExpression[]

num = {1., E, \[Pi], FortranForm[10.^10]} // N
Head[#] & /@ num
str = ToString[#] & /@ num
Head[#] & /@ str

but note the output of

exp = ToExpression[#] & /@ str
Head[#] & /@ exp

Define

n2s[s_?StringQ] := Block[
  {u, o},
  u = StringToStream[s];
  o = Read[u, Number];
  Close[u];
  o
  ]

Then try again:

n2s[#] & /@ str
Head[#] & /@ %
POSTED BY: David Annetts
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract