[R] how to get a numeric vector?
Avi Gross
@v|gro@@ @end|ng |rom ver|zon@net
Mon Oct 5 01:50:43 CEST 2020
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) but here is one:
unlist( map2(a, b, `:`) )
Or more explicitly in an extended length-4 vector example:
Library(purr)
alpha <- c(1, 4, 10, 20)
beta <- c(5, 8, 19, 27)
unlist(map2(.x=alpha,
.y=beta,
.f=`:`))
Result:
[1] 1 2 3 4 5 4 5 6 7 8 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27
Be warned the `:` operator happily works with descending or negative numbers
as well as numbers with decimal points. You do NOT want to call the above
uses of `:` unless you have no NA or NaN or Inf in your original vectors.
-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of vod vos via R-help
Sent: Sunday, October 4, 2020 6:47 PM
To: r-help <r-help using r-project.org>
Subject: [R] how to get a numeric vector?
Hi,
a <- c(1, 4)
b <- c(5, 8)
a:b
[1] 1 2 3 4 5
Warning messages:
1: In a:b : numerical expression has 2 elements: only the first used
2: In a:b : numerical expression has 2 elements: only the first used
how to get:
c(1:5, 4:8)
Thanks.
______________________________________________
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.
More information about the R-help
mailing list