rep(x, ...) rep.int(x, times) rep_len(x, length.out)
x
: numeric vector, factor, list etc.
...
: arguments including times (default = 1), length.out, each (each elements how many times)
> rep(8,4)[1] 8 8 8 8 > rep(NA,6)[1] NA NA NA NA NA NA > rep(1:5)
[1] 1 2 3 4 5
Repeat 1 to 5 two times:
> x <- rep(1:5,2) > x
[1] 1 2 3 4 5 1 2 3 4 5
Convert to a 5 × 2 matrix:
> dim(x) <- c(5,2) > x
[,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 2 4 [2,] 2 4 1 3 5
Each element replicates two times:
> x <- rep(1:5,each=2) > x
[1] 1 1 2 2 3 3 4 4 5 5
Convert to a 5 × 2 matrix:
> dim(x) <- c(5,2) > x
[,1] [,2] [,3] [,4] [,5] [1,] 1 2 3 4 5 [2,] 1 2 3 4 5
The repeat times of each elements can be different:
> rep(1:5,c(2,1,3,2,0))[1] 1 1 2 3 3 3 4 4 > rep(c(3,5,12),c(4,2,5))[1] 3 3 3 3 5 5 12 12 12 12 12
length.out
or len
determines the desired length of the return vector.
> rep(1:5,length.out=8)[1] 1 2 3 4 5 1 2 3 > rep(1:5,each=2, len=13)[1] 1 1 2 2 3 3 4 4 5 5 1 1 2
Quick and simple version of length specified repeat:
> rep_len(1:3,10)[1] 1 2 3 1 2 3 1 2 3 1
> rep.int(1:5,2)
[1] 1 2 3 4 5 1 2 3 4 5
Repeat a factor:
> x <- factor(LETTERS[1:6]) > names(x) <- 1:6 > x1 2 3 4 5 6 A B C D E F Levels: A B C D E F > rep(x, 2)1 2 3 4 5 6 1 2 3 4 5 6 A B C D E F A B C D E F Levels: A B C D E F
Repeat a list:
> x <- list(cost=1000.24,urgent="yes") > x$cost [1] 1000.24 $urgent [1] "yes" > rep(x,2)$cost [1] 1000.24 $urgent [1] "yes" $cost [1] 1000.24 $urgent [1] "yes"