How to append rows to an R data frame

前端 未结 7 1567
太阳男子
太阳男子 2020-11-28 02:04

I have looked around StackOverflow, but I cannot find a solution specific to my problem, which involves appending rows to an R data frame.

I am initializing an empty

7条回答
  •  悲哀的现实
    2020-11-28 02:41

    A more generic solution for might be the following.

        extendDf <- function (df, n) {
        withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
        nr          <- nrow (df)
        colNames    <- names(df)
        for (c in 1:length(colNames)) {
            if (is.factor(df[,c])) {
                col         <- vector (mode='character', length = nr+n) 
                col[1:nr]   <- as.character(df[,c])
                col[(nr+1):(n+nr)]<- rep(col[1], n)  # to avoid extra levels
                col         <- as.factor(col)
            } else {
                col         <- vector (mode=mode(df[1,c]), length = nr+n)
                class(col)  <- class (df[1,c])
                col[1:nr]   <- df[,c] 
            }
            if (c==1) {
                newDf       <- data.frame (col ,stringsAsFactors=withFactors)
            } else {
                newDf[,c]   <- col 
            }
        }
        names(newDf) <- colNames
        newDf
    }
    

    The function extendDf() extends a data frame with n rows.

    As an example:

    aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
    extendDf (aDf, 2)
    #      l i n c                   t
    # 1  TRUE 1 1 a 2016-07-06 17:12:30
    # 2 FALSE 0 0 a 1970-01-01 01:00:00
    # 3 FALSE 0 0 a 1970-01-01 01:00:00
    
    system.time (eDf <- extendDf (aDf, 100000))
    #    user  system elapsed 
    #   0.009   0.002   0.010
    system.time (eDf <- extendDf (eDf, 100000))
    #    user  system elapsed 
    #   0.068   0.002   0.070
    

提交回复
热议问题