How to append rows to an R data frame

前端 未结 7 1505
太阳男子
太阳男子 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:47

    Let's benchmark the three solutions proposed:

    # use rbind
    f1 <- function(n){
      df <- data.frame(x = numeric(), y = character())
      for(i in 1:n){
        df <- rbind(df, data.frame(x = i, y = toString(i)))
      }
      df
    }
    # use list
    f2 <- function(n){
      df <- data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)
      for(i in 1:n){
        df[i,] <- list(i, toString(i))
      }
      df
    }
    # pre-allocate space
    f3 <- function(n){
      df <- data.frame(x = numeric(1000), y = character(1000), stringsAsFactors = FALSE)
      for(i in 1:n){
        df$x[i] <- i
        df$y[i] <- toString(i)
      }
      df
    }
    system.time(f1(1000))
    #   user  system elapsed 
    #   1.33    0.00    1.32 
    system.time(f2(1000))
    #   user  system elapsed 
    #   0.19    0.00    0.19 
    system.time(f3(1000))
    #   user  system elapsed 
    #   0.14    0.00    0.14
    

    The best solution is to pre-allocate space (as intended in R). The next-best solution is to use list, and the worst solution (at least based on these timing results) appears to be rbind.

    0 讨论(0)
提交回复
热议问题