Re: SortBy
- To: mathgroup at smc.vnet.net
- Subject: [mg118251] Re: SortBy
- From: Dana DeLouis <dana01 at me.com>
- Date: Sun, 17 Apr 2011 19:15:58 -0400 (EDT)
> > KS = {{300, 48, 2}, {500, 23, 5}, {120, 55, 7}, {40, 32, 1}}; > > I want to sort it by second element. > > But if I want to use SortBy, how to do that? > > While there are functions First and Last, there is no Second and Third, > but maybe that's an inexpensive possibility to increase the number of > functions in the next version even more :-). > > SortBy[KS, #[[2]] &] I was just playing around with this idea. There's probably a better way if you wanted to go this route. (* Skip the reserve word First, and carry out as far as you want *) var={Null, Second, Third, Forth, Fifth, Sixth, Seventh}; MapIndexed[Function[{n,v},n := #1[[v]] & ],var]//Quiet; t=Partition[RandomSample[Range@12],4] {{2,10,7,5},{3,4,12,6},{9,8,11,1}} SortBy[t,First] {{2,10,7,5},{3,4,12,6},{9,8,11,1}} SortBy[t,Second] {{3,4,12,6},{9,8,11,1},{2,10,7,5}} SortBy[t,Third] {{2,10,7,5},{9,8,11,1},{3,4,12,6}} SortBy[t,Forth] {{9,8,11,1},{2,10,7,5},{3,4,12,6}} = = = = = Dana Mac, Ver 8