map each vector element to a vector

39 views Asked by At

I use Daru and have a vector.

vector = Daru::Vector.new({ a: 1, b: 2, c: 3})

Now, I have a function which I'd like to apply on each element and obtain result as vector.

// example function; a function I'd like to apply on each element
f = ->(num) { rand(num) }

vector.some_mapping_method(&f)
# => expects Vector of { a: rand(1), b: rand(2), c: rand(3) }

I tried .map method, but that returns result in an array.

Question

How can I map each element in a vector and return a vector, which has the same index as the original one?

In python terms, I want .map method of pd.Series in pandas.

1

There are 1 answers

0
janpeterka On BEST ANSWER

There are map! and recode methods for Vector (see documentation)

So, you should be able to do either:
vector.map! {|value| rand(value)}
or
new_vector = vector.recode {|value| rand(value)}
(or vector = vector.recode {|value| rand(value)} if you want to change your vector in place)

I used recode in my code, not map!, so I don't guarantee it works this way. Documentation on map! is not the best