1
$\begingroup$

I'm trying to use "Do" to change the entries in a column of a dataset using two adjacent columns. When I simply assign i and execute the lin for each value of i, it works but when I enclose it in Do, the Dataset becomes null.

The code I'm trying to use is:

sample5 =Do[ReplacePart[sample4, {i, "GeoPosition"} ->
GeoPosition[{sample4[i, "Latitude"], 
sample4[i, "Longitude"]}]], {i, Length[sample4]}]

The trial Dataset is:

Dataset[{<|"Facility Name" -> "Stanford Health Care", "Latitude" -> 37.4330139, "Longitude" -> -122.1758423,"GeoPosition" -> "GeoPosition"|>, <|"Facility Name" ->  "California Pacific Medical Center - California West Campus \  Hospital", "Latitude" -> 37.7861157, "Longitude" -> -122.4560595,"GeoPosition" -> "GeoPosition"|>} ]

Mathematica 11.3 on Mac Os Sierra 10.12.6

$\endgroup$
  • 1
    $\begingroup$ There is almost never a good reason to use Do. Try Table instead. $\endgroup$ – David G. Stork Mar 13 '19 at 20:54
  • 1
    $\begingroup$ There are plenty of good reasons to use Do (haven't checked if this is one of them) $\endgroup$ – Jason B. Mar 13 '19 at 20:56
  • $\begingroup$ Can Table be used to modify a Dataset and still result in a Dataset? $\endgroup$ – user5091 Mar 13 '19 at 20:56
2
$\begingroup$

Your first problem is that

ReplacePart[ sample4, rules]

does not modify sample4, but in fact returns a new Dataset with the desired replacement.

The reason that your example5 is Null is because that is what Do returns. Do is a wonderful function, but it won't return anything (it just does something).

Minimal modification to your code:

sample5 = sample4;
Do[
    sample5 = ReplacePart[
        sample5,
        {i, "GeoPosition"} -> GeoPosition[{sample5[i, "Latitude"], sample5[i, "Longitude"]}]
    ],
    {i, Length @ sample4}
] 

For this particular use case, you don't need to loop at all, you can do it all in one ReplacePart command:

ReplacePart[sample4,
    {i_, "GeoPosition"} :> GeoPosition[{sample4[i, "Latitude"], sample4[i, "Longitude"]}]
]
$\endgroup$
2
$\begingroup$

For a functional approach you may use Query directly or implicitly with Dataset. Taking sample4 as in OP then

direct use with,

Query[All, <|#, "GeoPosition" -> GeoPosition@{#["Latitude"], #["Longitude"]}|> &]@sample4

and implicit use with Slot syntax sugar

sample4[All, <|#, "GeoPosition" -> GeoPosition@{#Latitude, #Longitude}|> &]

Both of the above give

Mathematica graphics

Hope this helps.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.