[R] how to get a numeric vector?
Martin Maechler
m@ech|er @end|ng |rom @t@t@m@th@ethz@ch
Mon Oct 5 10:57:49 CEST 2020
>>>>> Avi Gross via R-help
>>>>> on Sun, 4 Oct 2020 19:50:43 -0400 writes:
> Always hard to tell if THIS is a homework project. As with
> most things in R, if you can not find at least a dozen
> ways to do it, it is not worth doing.
> The question (way below) was how to take two vectors of
> length two and make a longer results based on using the
> ":" operator to generate a range between the first element
> of each array and then between the second elements and
> return the combined results as a vector.
> Using simple loops on the length of the two vectors you
> want combined this way can be done either in-line or by
> making a simple function.
> Something like this:
> results = c()
> for (index in 1:length(a)) {
> results <- c(results, a[index]:b[index])
> }
> The above generalizes to any size vectors of the same length.
> There are probably lots of ways to do this using functional programming
> (after loading the tidyverse or just purrr)
Well, no (to your "(....)") !
Functional programming is part of base R; no need to install any
tidy or untidy package :
a <- c(1, 4)
b <- c(5, 8)
unlist( Map(`:`, a,b) )
works perfectly.
... as does the also nice and simple (base R)
solution that Tanvir Ahamed already posted :
unlist(as.vector(mapply(seq,a,b)))
More information about the R-help
mailing list