Re: any better to apply a function to second column?
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg529] Re: [mg507] any better to apply a function to second column?
- From: Xah Y Lee <xyl10060 at fhda.edu>
- Date: Thu, 9 Mar 1995 14:17:02 -0800 (PST)
Problem: How to make a list {{a,1},{b,2},{c,3},{d,4}} to become {{ a, f[1]}, { b, f[2]}, { c, f[3]}, { d, f[4]}}... and the more generalized problem is how to apply a function to nth column. Here is a summary of solutions. Roughly in order of speed. Clear[mylist] mylist = Table[ {i,i x }, {i,1,2000}]; (* 5.7 *) mylist2 = Transpose@mylist; Transpose[{ mylist2[[1]], f/@ mylist2[[2]] }]; (* 6.6*) Apply[{#1,f[#2]}&, mylist,{1}]; (* 6.6 *) mylist /. {x_,y_}:>{x,f[y]}; (* 8.0 *) Map[MapAt[f, #, {2}]&, mylist]; (* 8.5 *) Apply[{#1, f[#2], ##3}&, mylist, {1}]; (* 12.2 *) {#[[1]], f[#[[2]]]}& /@ mylist; (* 15.3 *) Replace[#,{x_,y_}:>{x,f[y]}]& /@ mylist; (* 39.6 *) MapAt[f,mylist, Table[ {i,2}, {i,Length[mylist]}]]; %%%%%%%==%%%%%%==%%%%%==%%%%==%%%==%%==% Xah Lee xyl10060 at tiptoe.fhda.edu Mountain View, CA