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$
4
  • 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$ Mar 30 '20 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 '20 at 16:32
  • 2
    $\begingroup$ data[[;; , 1]] = Sqrt[data[[;; , 1]]] $\endgroup$
    – Fraccalo
    Mar 30 '20 at 16:36
  • 2
    $\begingroup$ data[[All, 1]] = Sqrt[data[[All, 1]]] . $\endgroup$ Mar 30 '20 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
$\endgroup$
1
  • 1
    $\begingroup$ Wow! That gives me material to breed over. Great! $\endgroup$
    – user57467
    Mar 30 '20 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}}
$\endgroup$
2
  • $\begingroup$ I can understand your first solution, but what does "@@@ # &" in the second part really mean? $\endgroup$
    – user57467
    Mar 31 '20 at 4:21
  • $\begingroup$ @user57467, ` foo@@@#&` replaces heads at level 1 of input expression with foo (see Apply) $\endgroup$
    – kglr
    Mar 31 '20 at 4:52
6
$\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}}
$\endgroup$
1
  • 1
    $\begingroup$ I haver never seen this symbol. Looks good! :) $\endgroup$
    – user57467
    Mar 31 '20 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.