[R] OK, next Q - a sort of factorial on a vector

Sarah Goslee @@r@h@go@|ee @end|ng |rom gm@||@com
Tue Jun 20 19:38:19 CEST 2023


Well, I think this is reasonable elegant, but ymmv. Turning it into a
function and removing NA values is left for you.

> x <- 1:5
> unlist(sapply(seq(1, length(x) - 1), function(i){x[i] * x[seq(i + 1, length(x))]}))
 [1]  2  3  4  5  6  8 10 12 15 20
>
> x <- c(1, 2, NA, 4, 5)
> unlist(sapply(seq(1, length(x) - 1), function(i){x[i] * x[seq(i + 1, length(x))]}))
 [1]  2 NA  4  5 NA  8 10 NA NA 20

Sarah

On Tue, Jun 20, 2023 at 1:15 PM Philip Rhoades via R-help
<r-help using r-project.org> wrote:
>
> People,
>
> What I mean is, is there an elegant way to do this:
>
> This:
>
>    !(1,2,3,4,5)
>
> would give this:
>
>    (2,3,4,5, 6,8,10, 12,15, 20)
>
> and this:
>
>    !(1,2,NA,4,5)
>
> would give this:
>
>    (2,4,5, 8,10, 20)
>
> ?
>
> Thanks!
>
> Phil.
> --
> Philip Rhoades
>
> PO Box 896
> Cowra  NSW  2794
> Australia
> E-mail:  phil using pricom.com.au
>
> ______________________________________________
> R-help using 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.



-- 
Sarah Goslee (she/her)
http://www.numberwright.com



More information about the R-help mailing list