user9292
user9292

Reputation: 1145

repeat Data N times in R

The data I have contain three variables. There are three unique IDs and each has multiple records.

ID <- c(rep(1,2), rep(2,1), rep(3,2))
y0 <- c(rep(5,2), rep(3,1), rep(1,2))
z0 <- c(rep(1,2), rep(13,1), rep(4,2))

dat1 <- data.frame(ID, y0,z0)

What I am trying to is repeat the whole data N times (N needs to be a parameter), and I need to add a new column with the repetition number.

So if N = 2, the new data look like:

rep <- c(rep(1,2), rep(2,2), rep(1,1), rep(2,1), rep(1,2), rep(2,2))
ID <- c(rep(1,4), rep(2,2), rep(3,4))
y0 <- c(rep(5,4), rep(3,2), rep(1,4))
z0 <- c(rep(1,4), rep(13,2), rep(4,4))

dat2 <- data.frame(rep, ID, y0,z0)

Upvotes: 1

Views: 1173

Answers (1)

akrun
akrun

Reputation: 887098

We replicate the sequence of rows and order it later to get the expected output

res <- cbind(rep = rep(seq_len(2), each = nrow(dat1)), dat1[rep(seq_len(nrow(dat1)), 2),])
resN <- res[order(res$ID),]
row.names(resN) <- NULL
all.equal(dat2, resN, check.attributes = FALSE)
#[1] TRUE

Or another option is to replicate into a list and then with Map create the 'rep' column (it is not recommended to have function names as column names, object names etc.) and rbind the list elements

res1 <- do.call(rbind, Map(cbind, rep = seq_len(2), replicate(2, dat1, simplify = FALSE)))
res2 <- res1[order(res1$ID),]
row.names(res2) <- NULL
all.equal(dat2, res2, check.attributes = FALSE)
#[1] TRUE

Upvotes: 1

Related Questions