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.
There are
map!
andrecode
methods forVector
(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, notmap!
, so I don't guarantee it works this way. Documentation onmap!
is not the best