The R function rep() replicates each element of a vector:
> rep(c(\"A\",\"B\"), times=2)
[1] \"A\" \"B\" \"A\" \"B\"
This is like the list m
What do you think about this way?
To repeat a value:
>>> repetitions=[]
>>> torep=3
>>> nrep=5
>>> for i in range(nrep):
>>> i=torep
>>> repetitions.append(i)
[3, 3, 3, 3, 3]
To repeat a sequence:
>>> repetitions=[]
>>> torep=[1,2,3,4]
>>> nrep= 2
>>> for i in range(nrep):
>>> repetitions=repetitions+torep
>>> print(repetitions)
[1, 2, 3, 4, 1, 2, 3, 4]
Here is my attempt at a clone of R
rep
:
def rep(x, times = 1, each = 1, length_out = None):
if not isinstance(times, list):
times = [times]
res = ''.join([str(i) * each for i in x])
if len(times) > 1:
res = ''.join(str(i) * m for i, m in zip(x, times))
else:
res = ''.join(res * times[0])
if length_out is None:
return res
else:
return res[0:length_out]
Reproduces the R
examples:
rep(range(4), times = 2)
rep(range(4), each = 2)
rep(range(4), times = [2,2,2,2])
rep(range(4), each = 2, length_out = 4)
rep(range(4), each = 2, times = 3)
with the exception that there is no recycling of shorter vectors/lists (imo this is the worst feature of R
).