Tom Wenseleers
Tom Wenseleers

Reputation: 7989

Julia - equivalent of R's rep() with times argument

I am looking for an idiomatic and compact way to achieve in Julia what I would do in R with

v1=1:5;v2=5:1;out=rep(v1,times=v2);out
# 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5

i.e. replicate each element in vector v1 a number of times given by the corresponding element in vector v2. Any thoughts?

Upvotes: 4

Views: 524

Answers (3)

GKi
GKi

Reputation: 39687

An option is to use fill..

vcat(fill.(1:5, 5:-1:1)...)'
#1×15 adjoint(::Vector{Int64}) with eltype Int64:
# 1  1  1  1  1  2  2  2  2  3  3  3  4  4  5

Or using inverse_rle from StatsBase.

using StatsBase
inverse_rle(1:5, 5:-1:1)'
#1×15 adjoint(::Vector{Int64}) with eltype Int64:
# 1  1  1  1  1  2  2  2  2  3  3  3  4  4  5

Upvotes: 1

Chris Rackauckas
Chris Rackauckas

Reputation: 19142

Try using VectorizedRoutines.jl:

# Pkg.clone("https://github.com/ChrisRackauckas/VectorizedRoutines.jl")
# Will be Pkg.add("VectorizedRoutines") after being added to package system
using VectorizedRoutines
v1=1:5
v2 = 5:-1:1
R.rep(v1,each = v2)

The implementation is based off of RLEVectors.jl via the suggestion of aireties (improved the typing a bit so you don't have to collect).

This is a package I started up to get together all the vectorized routines from R/MATLAB/Python so that porting functions (and ideas) easier to Julia. Feel free to open issues on the Github repository for suggestions of functions to implement, functions implemented in other packages I should know about, syntax not matching other languages, or if there are any other problems. Also feel free to give a pull request if you implement any functions like this. If you need help, don't be afraid make a pull request with the basic function and I can help you out.

Upvotes: 2

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10990

Here is one option using array comprehensions:

v1 = 1:5;
v2 = 5:-1:1;

out = vcat([ [v1[idx] for n = 1:v2[idx]] for idx = 1:length(v1) ]...)

Also, if you want something closer to the R syntax, you can use the rep() function from the RLEVectors package:

## Pkg.add("RLEVectors")
using RLEVectors
out2 = rep(collect(v1), each = collect(v2))

As is, out2 will be a vector with Run Length Encoding. It will function similarly to most other vectors as is, with memory and computation speedups in some cases. But, if you want a regular vector from it, just use collect(out2).

Upvotes: 2

Related Questions