A. Hartman
A. Hartman

Reputation: 253

Is there a rep() function in a package in Julia?

I am looking for a function in Julia that has can take values similar to this R code:

rep(1, ncol(X))

I know I can use the package DataFrames for the length function for the ncol() function in R, but I can't find a rep function in Julia. Thank you!

Upvotes: 9

Views: 2848

Answers (2)

GKi
GKi

Reputation: 39687

An option could be to use inverse_rle from StatsBase for R's rep using each.

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

Benchmark

using StatsBase, BenchmarkTools
@btime inverse_rle(1:10, 1:10)
#  68.641 ns (1 allocation: 496 bytes)

@btime vcat(fill.(1:10, 1:10)...)  # @Bogumił Kamiński
#  526.042 ns (12 allocations: 1.62 KiB)

Upvotes: 0

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69909

The equivalent of rep in Julia is repeat. As arguments it takes an AbstractArray and two keyword arguments innner (like each in R) and outer (like times in R). The benefit of repeat is that it works consistently with multidimensional arrays (you can have a look at the documentation for details).

For example:

julia> repeat([1,2,3], inner=2, outer=3)
18-element Array{Int64,1}:
 1
 1
 2
 2
 3
 3
 1
 1
 2
 2
 3
 3
 1
 1
 2
 2
 3
 3

in Julia gives you the same as:

> rep(c(1,2,3), each=2, times=3)
 [1] 1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3

in R.

EDIT: If you want to repeat a scalar use fill, e.g.:

julia> fill(1, 5)
5-element Array{Int64,1}:
 1
 1
 1
 1
 1

Upvotes: 12

Related Questions