Suppose I have a dataset a, featuring a column labeled n, whose values are all string representations of integer values. I want to generate a new dataset b identical to a in everyway, except that its n column contains the actual integers represented by the strings in a's n column.

The following strategy does not work, but at least it may convey what I'd like to do:

b = a;
b[[All, "n"]] = Dataset[<|"n" -> ToExpression[#]|> & /@ (Normal@a[[All, "n"]])];

(The second assignment above produces the error Set::partd: Part specification b[[All,n]] is longer than depth of object.)

Importantly, I want to do this in a way that is agnostic to the position of column n among the columns of a. (After all, the whole point of using named columns is to allow for such column-order-agnostic code.)

After a lot of trial-and-error I hit upon this:

b = Association[#, "n" -> ToExpression[#n]] & /@ a

...which strikes me as a very convoluted and counterintuitive way to perform a very natural operation. Is there clearer syntax for this sort of thing?


closed as off-topic by m_goldberg, LCarvalho, MarcoB, Itai Seggev, Edmund Jul 26 '17 at 10:35

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – m_goldberg, LCarvalho, MarcoB, Itai Seggev, Edmund
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ Does a[All, "n" -> FromDigits] work? $\endgroup$ – Carl Woll Jul 24 '17 at 15:03
  • $\begingroup$ @CarlWoll: Thanks, but no, I get the error OptionValue: Unknown option n for Query. $\endgroup$ – kjo Jul 24 '17 at 15:27
  • 3
    $\begingroup$ Then you should provide a MWE of the sort of dataset you are interested in. I think the relevant documentation example is here $\endgroup$ – Carl Woll Jul 24 '17 at 15:29

Contrived data. The 2nd column is populated with string representations of the numbers in the 1st column.

With[{n = 5},
 a = 
   Dataset[<|"i" -> #, "n" -> ToString[#]|> & /@ RandomSample[Range[101, 199], n]]]


Dataset with 2nd column converted from strings to numbers.

b = a[All, {"n" -> ToExpression}]


a[All, "n"] // Normal // InputForm

{"155", "167", "105", "116", "107"}

b[All, "n"] // Normal // InputForm

{155, 167, 105, 116, 107}


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