[R] Reduce woes

Stefan Kruger stefan.kruger at gmail.com
Wed Jul 27 17:20:22 CEST 2016


Hi -

I'm new to R.

In other functional languages I'm familiar with you can often seed a call
to reduce() with a custom accumulator. Here's an example in Elixir:

map = %{"one" => [1, 1], "three" => [3], "two" => [2, 2]}
map |> Enum.reduce(%{}, fn ({k,v}, acc) -> Map.update(acc, k,
Enum.count(v), nil) end)
# %{"one" => 2, "three" => 1, "two" => 2}

In R-terms that's reducing a list of vectors to become a new list mapping
the names to the vector lengths.

Even in JavaScript, you can do similar things:

list = { one: [1, 1], three: [3], two: [2, 2] };
var result = Object.keys(list).reduceRight(function (acc, item) {
  acc[item] = list[item].length;
  return acc;
}, {});
// result == { two: 2, three: 1, one: 2 }

In R, from what I can gather, Reduce() is restricted such that any init
value you feed it is required to be of the same type as the elements of the
vector you're reducing -- so I can't build up. So whilst I can do, say

> Reduce(function(acc, item) { acc + item }, c(1,2,3,4,5), 96)
[1] 111

I can't use Reduce to build up a list, vector or data frame?

What am I missing?

Many thanks for any pointers,

Stefan



-- 
Stefan Kruger <stefan.kruger at gmail.com>

	[[alternative HTML version deleted]]



More information about the R-help mailing list