Christoph_J Christoph_J - 1 year ago 119
R Question

Alternative to expand.grid for data.frames

I have a data.frame

and I want that every row in this
is duplicated
times and that a new column is added that counts from 1 to
for each row in

I know, it sounds pretty complicated, but what I basically want is to apply
. Here is an ugly workaround and I have the feeling that there most be an easier solution (maybe even a base-R function?):

df <- data.frame(ID = rep(letters[1:3], each=3),
CatA = rep(1:3, times = 3),
CatB = letters[1:9])
lengthTime <- 3
nrRow <- nrow(df)
intDF <- df
for (i in 1:(lengthTime - 1)) {
df <- rbind(df, intDF)
df$Time <- rep(1:lengthTime, each=nrRow)

I thought that I could just use
expand.grid(df, 1:lengthTime)
, but that does not work.
did not bring any luck either. So does anyone know a good solution?

Answer Source

Why not just something like df[rep(1:nrow(df),times = 3),] to extend the data frame, and then add the extra column just as you have above, with df$Time <- rep(1:lengthTime, each=nrRow)?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download