[R] Is there a sexy way ...?

Lennart Kasserra |enn@rt@k@@@err@ @end|ng |rom gm@||@com
Sat Sep 28 07:52:07 CEST 2024


Hi Rolf,

this topic is probably already saturated, but here is a tidyverse solution:

```

library(purrr)

x <- list(
   `1` = c(7, 13, 1, 4, 10),
   `2` = c(2, 5,  14, 8, 11),
   `3` = c(6, 9, 15, 12, 3)
)

x |>
   pmap(~ c(..1, ..2, ..3)) |>
   reduce(c)

#> [1]  7  2  6 13  5  9  1 14 15  4  8 12 10 11  3

```

Here, we map over the elements of the list in parallel (hence pmap), 
always combining the elements at the current position into a vector, 
which will result in a list like this:

```

[[1]]
[1] 7 2 6

[[2]]
[1] 13  5  9

...

```

And then we reduce this resulting list into a vector by successively 
combining its elements with `c()`. I think the formula syntax is a bit 
idiosyncratic, you could also do this with an anonymous function like 
pmap(\(`1`, `2`, `3`) c(`1`, `2`, `3`)), or if the list was unnamed as 
pmap(\(x, y, z) c(x, y, z)).

I personally find the tidyverse-esque code to be very explicit & 
readable, but given base R can do this very concisely one might argue 
that it is superfluous to bring in an extra library for this. I think 
Bert's solution (
`c(do.call(rbind, x))`) is great if `f` has no substantive meaning, and 
Deepayan's solution (`unsplit(x, f)`) is perfect in case it does - does 
not get much sexier than that, I am afraid.

Best,

Lennart


Am 27.09.24 um 05:55 schrieb Rolf Turner:
> I have (toy example):
>
> x <- list(`1` = c(7, 13, 1, 4, 10),
>            `2` = c(2, 5,  14, 8, 11),
>            `3` = c(6, 9, 15, 12, 3))
> and
>
> f <- factor(rep(1:3,5))
>
> I want to create a vector v of length 15 such that the entries of v,
> corresponding to level l of f are the entries of x[[l]].  I.e. I want
> v to equal
>
>      c(7, 2, 6, 13, 5, 9, 1, 14, 15, 4, 8, 12, 10, 11, 3)
>
> I can create v "easily enough", using say, a for-loop.  It seems to me,
> though, that there should be sexier (single command) way of achieving
> the desired result.  However I cannot devise one.
>
> Can anyone point me in the right direction?  Thanks.
>
> cheers,
>
> Rolf Turner
>



More information about the R-help mailing list