rep()
function replicates the values in x. It is a generic function.rep.int
and rep_len
are faster simplified versions for two common cases. They are not generic.rep(x, ...)
rep.int(x, times)
rep_len(x, length.out)
The parameters are:
x
: vector or factor to be repeated.times
: an integer valued vector giving the times to repeat each element.length.out
: length of the outputeach
: the times each element in x is repeated
rep()
:rep(1:3, times = 2) #from 1 to 3, 2 times.
## [1] 1 2 3 1 2 3
rep(1:3, 2) #from 1 to 3, 2 times.
## [1] 1 2 3 1 2 3
rep(1:3, each = 2) #from 1 to 3, each value 2 times
## [1] 1 1 2 2 3 3
rep(1:3, c(2,2,2)) #time of each value from 1 to 3 is given by a vector
## [1] 1 1 2 2 3 3
rep(1:3, c(0,1,2))
## [1] 2 3 3
rep(1:3, each = 3, len = 3) # 3 first values
## [1] 1 1 1
rep(1:3, each = 3, len = 12) # 12 integers, 3 numbers are recycled
## [1] 1 1 1 2 2 2 3 3 3 1 1 1
rep(1:3, each = 3, times = 3)
## [1] 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3
rep.int()
:x = data.frame(1:10,21:30)
colnames(x) = c('A','B')
x
## A B
## 1 1 21
## 2 2 22
## 3 3 23
## 4 4 24
## 5 5 25
## 6 6 26
## 7 7 27
## 8 8 28
## 9 9 29
## 10 10 30
rep(x, times = 2)
## $A
## [1] 1 2 3 4 5 6 7 8 9 10
##
## $B
## [1] 21 22 23 24 25 26 27 28 29 30
##
## $A
## [1] 1 2 3 4 5 6 7 8 9 10
##
## $B
## [1] 21 22 23 24 25 26 27 28 29 30
rep.int(x, times = 2)
## [[1]]
## [1] 1 2 3 4 5 6 7 8 9 10
##
## [[2]]
## [1] 21 22 23 24 25 26 27 28 29 30
##
## [[3]]
## [1] 1 2 3 4 5 6 7 8 9 10
##
## [[4]]
## [1] 21 22 23 24 25 26 27 28 29 30
rep_len()
:rep(1,6)
## [1] 1 1 1 1 1 1
rep_len(1,6) #same result
## [1] 1 1 1 1 1 1
rep(1:5, 10) #number of times = 10
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
## [36] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
rep_len(1:5, 10) #length = 10
## [1] 1 2 3 4 5 1 2 3 4 5
par(mfrow = c(2,2))
y = c(1,2,3)
plot(y, type = 'b', col = 'gold')
plot(rep(y, time = 2), type = 'b', col = 'darkturquoise')
plot(rep(y, time = 2, each = 2), type = 'b', col = 'darkviolet')
plot(rep(y, time = 2, each = 2, len = 6), type = 'b', col = 'deeppink')
No comments:
Post a Comment