[R] Reduce woes

Peter Langfelder peter.langfelder at gmail.com
Wed Jul 27 19:22:56 CEST 2016


If you have a simple list of vectors (call it lst), use

lengths = sapply(lst, length)

In general, you may want to look at functions lapply and sapply which
apply a function over a list, in this case the function length().

Peter

On Wed, Jul 27, 2016 at 8:20 AM, Stefan Kruger <stefan.kruger at gmail.com> wrote:
> 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]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list