1

I have a vector that I would like to increase the elements based on another vector.
How can I increase the elements in my vector without having to manually type it out? I want to use the two vectors

NumberofTimes<-c(4,1,2,3)
Spread<-c(0.060,0.170,0.140,0.070)
```
I.e. I want a vector with 4 of the 0.060, 1 of the 0.170, 2 of the 0.140, etc.
Instead of writing: 
  
```
Spread<-c(0.060,0.060,0.060,0.060,0.170,0.140,0.140,0.070,0.070,0.070)
```
Jessi
  • 48
  • 4

3 Answers3

1

Base R rep function with times argument

> rep(Spread, times = NumberofTimes)
 [1] 0.06 0.06 0.06 0.06 0.17 0.14 0.14 0.07 0.07 0.07
polkas
  • 3,797
  • 1
  • 12
  • 25
-1

Try this using mapply() and a function with rep() to wrap sequences between Spread and NumberofTimes. Here the code:

#Data
NumberofTimes<-c(4,1,2,3)
Spread<-c(0.060,0.170,0.140,0.070)
#Apply
vecval <- unlist(mapply(function(x,y) rep(x,y),x=Spread,y=NumberofTimes))

Output:

[1] 0.06 0.06 0.06 0.06 0.17 0.14 0.14 0.07 0.07 0.07
Duck
  • 39,058
  • 13
  • 42
  • 84
-1

An option with Map

unlist(Map(rep, Spread, NumberofTimes))
akrun
  • 874,273
  • 37
  • 540
  • 662