Alternative to expand.grid for data.frames

前端 未结 6 1501
误落风尘
误落风尘 2020-11-27 16:22

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

6条回答
  •  甜味超标
    2020-11-27 17:08

    It's been a while since this question was posted, but I recently came across it looking for just the thing in the title, namely, an expand.grid that works for data frames. The posted answers address the OP's more specific question, so in case anyone is looking for a more general solution for data frames, here's a slightly more general approach:

    expand.grid.df <- function(...) Reduce(function(...) merge(..., by=NULL), list(...))
    
    # For the example in the OP
    expand.grid.df(df, data.frame(1:lengthTime))
    
    # More generally
    df1 <- data.frame(A=1:3, B=11:13)
    df2 <- data.frame(C=51:52, D=c("Y", "N"))
    df3 <- data.frame(E=c("+", "-"))
    expand.grid.df(df1, df2, df3)
    

提交回复
热议问题