-2

I´m trying to append the result of a for loop which produces a vector with different length, after each iteration. I need to have the result of each loop side by side in each column. This is the error I get:

Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 3650

I have tested this with vectors with the same size but I get the same error. I have tried some of the solutions that I found here: Append data frames together in a for loop but whithout success, some of them work but results appear in a single column . How can I fix this?

d = NULL
for (i in 1:10) {

  # vector output
  model <- # vector with different length for each iteration

  # add vector to a dataframe
  df <- data.frame(model)

}

df_total <- cbind(d,df)
Manuel Almeida
  • 183
  • 2
  • 9
  • 1
    Please consider our guidelines on reproducible examples: https://stackoverflow.com/a/5963610/6574038 – jay.sf Feb 23 '21 at 10:50
  • 1) In the loop, you are rewriting `df` 10 times and only the last one is `cbind`ed with `d`; 2) the error message says *"Error etc number of rows: 0, 3650"* and in fact `d <- NULL` has 0 rows. Therefore, in the last iteration your model must be producing a `df` with 3650 rows. – Rui Barradas Feb 23 '21 at 10:53
  • 3) Consider `d <- lapply(1:10, function(i) {model <- code; data.frame(model)}); df_total <- do.call(cbind, d)`. – Rui Barradas Feb 23 '21 at 10:55
  • Thank you Rui, your solution solved the inital error, but now I have another. My vectors have different length so I cant use cbind. Can you help me with an alternative approach? – Manuel Almeida Feb 23 '21 at 13:31

1 Answers1

1

Use lapply to return your code which will generate a list. Since the vector is of unequal length you can append NA's to vector of shorter length and bind them together.

tmp <- lapply(1:10, function(x) {your code here})
n <- max(lengths(tmp))
result <- data.frame(sapply(tmp, `[`, 1:n))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213