2 views

I want to generate a data frame as:

1 1 6 6 10 10 ...

2 2 7 7 11 11 ...

3 3 8 8 12 12 ...

4 4 9 9 13 13 ...

5 5     14 14 ...

15 15 ...

The variables are:

n (repeat) and m(total number of columns) and k(k=the prior columns's end number+1,for example: 6=5+1, and 10=9+1), and different number length of row to create a table.

I know I can use like:

rep(list(1:5,6:9,10:15), each = 2)),

but how to make them as parameters using a general expression to list (1:5,6:9,10:15,..use n,m,k expression...).

by (108k points)

I think with the help of the following code, you can achieve your goal:

#Number of times to repeat

r <- 2

#Length of each sequence

len <- c(5, 4, 6)

#Get the end of the sequence

end <- cumsum(Glen)

#Calculate the start of each sequence

start <- c(1, end[-length(end)] + 1)

#Create a sequence of start and end and repeat it r times

Map(function(x, y) rep(seq(x, y), r), start, end)

#[[1]]

# [1] 1 2 3 4 5 1 2 3 4 5

#[[2]]

#[1] 6 7 8 9 6 7 8 9

#[[3]]

# [1] 10 11 12 13 14 15 10 11 12 13 14 15

You can also unlist to get it as one vector.

unlist(Map(function(x, y) rep(seq(x, y), r), start, end))

If you are a beginner and want to know more about R then do check out the R programming tutorial.