From: Ara.T.Howard@... Date: 2004-10-13T17:24:34+09:00 Subject: Re: The Challenge of R On Wed, 13 Oct 2004, trans. (T. Onoma) wrote: > Here's a coding challenge you. > > The R language has the following nifty features for working with arrays. To > what degree can you get Ruby to do the same? > > The solution that is closest/nicest gets forever embedded in my growing > library of Ruby enhancements, and it's author's name wrapped in shiny > asterisks and number signs! Joy, joy! :) > > Listing 1. Elementwise operations in R > >> a = 1:10 # Range of numbers 1 through 10 >> b = a+5 # Add 5 to each element >> b # Show b vector > [1] 6 7 8 9 10 11 12 13 14 15 > > Or you can operate selectively only on elements with certain indices, by using > an "index array": > > > Listing 2. Using index arrays to select elements > >> c = b # Make a (lazy) copy of b >> pos = c(1,2,3,5,7) # Change the prime indices >> c[pos] = c[pos]*10 # Reassign to indexed positions >> c # Show c vector > [1] 60 70 80 9 100 11 120 13 14 15 > > Or, maybe best of all, you can use a syntax much akin to list comprehensions > in Haskell or Python, and only operate on elements that have a desired > property: > > > Listing 3. Using predicates to select elements > >> d = c >> d[d %% 2 == 0] = -1 # Reassign -1 to all even elements >> d > [1] -1 -1 -1 9 -1 11 -1 13 -1 15 i did not write it, but narray does all that you want, and more, including being extremely fast, doing simply display of data in X, and working seamlessly with memory mapping: jib:~ > cat a.rb require 'narray' a = NArray[1..10] b = a + 5 p b c = b pos = 0,1,2,4,6 # adjust R's 1 based idx to ruby's 0 based c[pos] = c[pos] * 10 p c d = c d[(d % 2).eq(0).where] = -1 p d jib:~ > ruby a.rb NArray.int(10): [ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] NArray.int(10): [ 60, 70, 80, 9, 100, 11, 120, 13, 14, 15 ] NArray.int(10): [ -1, -1, -1, 9, -1, 11, -1, 13, -1, 15 ] you can thank Masahiro Tanaka for such a great work. http://www.ir.isas.ac.jp/~masa/ruby/index-e.html kind regards. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | When you do something, you should burn yourself completely, like a good | bonfire, leaving no trace of yourself. --Shunryu Suzuki ===============================================================================