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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…