Christoph_J Christoph_J - 3 months ago 19
R Question

Alternative to expand.grid for data.frames

I have a data.frame

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

I know, it sounds pretty complicated, but what I basically want is to apply
expand.grid
to
df
. 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.
outer
did not bring any luck either. So does anyone know a good solution?

Answer

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)?