[R] OK, next Q - a sort of factorial on a vector
Philip Rhoades
ph|| @end|ng |rom pr|com@com@@u
Tue Jun 20 19:45:59 CEST 2023
Ivan,
On 2023-06-21 03:32, Ivan Krylov wrote:
> В Wed, 21 Jun 2023 03:13:52 +1000
> Philip Rhoades via R-help <r-help using r-project.org> пишет:
>
>> This:
>>
>> !(1,2,3,4,5)
>>
>> would give this:
>>
>> (2,3,4,5, 6,8,10, 12,15, 20)
>
> Do you mean taking a product of every element of the vector with all
> following vector elements? A relatively straightforward way would be
> (given your vector stored in `x`):
>
> unlist(lapply(seq_along(x), function(i) x[i] * x[-(1:i)]))
Perfect!
> (I'm sure it could be golfed further.)
I will look at Sarah's suggestion too.
>> and this:
>>
>> !(1,2,NA,4,5)
>>
>> would give this:
>>
>> (2,4,5, 8,10, 20)
>
> The previous solution seems to give your vector interspersed a bunch of
> NAs, so one way to continue would be to filter it using v[!is.na(v)].
Exactly!
Thanks people - it would have taken forever to work that out myself (it
has been decades since I looked at R).
Phil.
--
Philip Rhoades
PO Box 896
Cowra NSW 2794
Australia
E-mail: phil using pricom.com.au
More information about the R-help
mailing list