5
$\begingroup$

I have the following data and want to replace only the first part in all sublists by the square root. It can be done by:

data = {{49, 35, 14}, {64, 40, 16}, {81, 45, 18}};
t2 = Transpose[{Sqrt /@ data[[All, 1]]}];
t3 = Table[Flatten[AppendTo[t2[[i]], data[[i, 2 ;; 3]]]], {i, 3}]

and I get

{{7, 35, 14}, {8, 40, 16}, {9, 45, 18}}

What is a shorter way using Replace or other methods (and/or using patterns)?

$\endgroup$
  • 3
    $\begingroup$ This data /. {a_Integer, b_Integer, c_Integer} :> {Sqrt[a], b, c} seems to satisfy your immediate requirement. Is that the kind of answer you want ? $\endgroup$ – High Performance Mark Mar 30 at 16:15
  • 2
    $\begingroup$ {Sqrt[#[[1]]], #[[2]], #[[3]]} & /@ data or {Sqrt[#[[1]]], Sequence @@ Rest@##} & /@ data or ReplacePart[#, 1 -> Sqrt[#[[1]]]] & /@ data $\endgroup$ – Bob Hanlon Mar 30 at 16:32
  • 1
    $\begingroup$ data[[;; , 1]] = Sqrt[data[[;; , 1]]] $\endgroup$ – Fraccalo Mar 30 at 16:36
  • 1
    $\begingroup$ data[[All, 1]] = Sqrt[data[[All, 1]]] . $\endgroup$ – Fred Simons Mar 30 at 16:44
12
$\begingroup$

Here are a few ways:

MapAt[Sqrt, data, {All, 1}]
Replace[data, {x_, y___} :> {Sqrt[x], y}, {1}]
data // Query[All, {1 -> Sqrt}]
SubsetMap[Sqrt, data, {All, 1}]
ReplacePart[data, {i_, 1} :> Sqrt[data[[i, 1]]]]
data2 = data;
data2[[All, 1]] = Sqrt[data2[[All, 1]]];
data2
| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ Wow! That gives me material to breed over. Great! $\endgroup$ – user57467 Mar 30 at 16:52
7
$\begingroup$
☺ = {#^(1/2), ##2} &;

☺ @@@ data
{{7, 35, 14}, {8, 40, 16}, {9, 45, 18}}

or

☺☺ = {#^(1/2), ##2} & @@@ # &;

☺☺ @ data
{{7, 35, 14}, {8, 40, 16}, {9, 45, 18}}
| improve this answer | |
$\endgroup$
  • $\begingroup$ I can understand your first solution, but what does "@@@ # &" in the second part really mean? $\endgroup$ – user57467 Mar 31 at 4:21
  • $\begingroup$ @user57467, ` foo@@@#&` replaces heads at level 1 of input expression with foo (see Apply) $\endgroup$ – kglr Mar 31 at 4:52
5
$\begingroup$

What kglr posted, but a bit more "golfed"

data = {{49, 35, 14}, {64, 40, 16}, {81, 45, 18}};

{√#, ##2} & @@@ data
{{7, 35, 14}, {8, 40, 16}, {9, 45, 18}}
| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ I haver never seen this symbol. Looks good! :) $\endgroup$ – user57467 Mar 31 at 4:25

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.