6
$\begingroup$

Let's say I have some data:

data={{a1,b1},{a2,b2},{a3,b3},{a4,b4},...} 

and I would like to apply the function:

f1[x_]=x*5 to every a_i element.

How can I do this?

The best solution I've found so far is to do:

MapAt[f1, data, {{1, 1}, {2, 1}, {3, 1}, {4, 1}...}] 

Up to the length of my data, but I'm sure there's a more efficient solution for this.

$\endgroup$
10
  • 6
    $\begingroup$ MapAt[f1, data, {All, 1}]? $\endgroup$ Commented May 24, 2016 at 16:42
  • $\begingroup$ Map[Apply[{f[#1], ##2} &], data], if you insist... but J.M.'s approach is best. $\endgroup$ Commented May 24, 2016 at 16:44
  • $\begingroup$ Transpose@{f1[#1], #2} & @@ Transpose@data If your f1 is Listable (and yours is ) that can give you significant speed increase. $\endgroup$ Commented May 24, 2016 at 16:50
  • 1
    $\begingroup$ also: {f1@#, #2} & @@@ data $\endgroup$ Commented May 24, 2016 at 23:44
  • 2
    $\begingroup$ @BlacKow #1 and # are equivalent. $\endgroup$ Commented May 25, 2016 at 7:16

1 Answer 1

8
$\begingroup$

There are a number of ways (if I understand aim),e.g.:

lst = data = {{a1, b1}, {a2, b2}, {a3, b3}, {a4, b4}}; lst /. {x_, y_} :> {f[x], y} MapAt[f, lst, {All, 1}] {f@#1, #2} & @@@ lst 
$\endgroup$
3
  • $\begingroup$ Whenever I do one of these solutions I get the resulting list $ {{a1,{b1}},{a2,{b2}},etc.}}$. How do I remove the resulting list around the second element? $\endgroup$ Commented Apr 24, 2020 at 14:48
  • $\begingroup$ @ElyEastman what input are you using. The code applies function to first part of each element $\endgroup$ Commented Apr 25, 2020 at 4:48
  • $\begingroup$ I realized I was using an incorrect input for my function. It was dividing by a list element, which would encapsulate bi in a list. $\endgroup$ Commented Apr 26, 2020 at 0:06

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.