How to create a data frame with vectors of different sizes?

Asked

Viewed 74 times

2

The result of the loop for each iteration is a vector. I intend to send this vector to a data.frame and then export it to Excel.

I basically use the cbind function to send each of my 10 model results to a data.frame. This small example works but only if the 10 outputs of the model have the same number of rows (this is because the cbind function only works if the columns of the data.frames have the same number of rows). The vectors I get have a different size. How can I get around this question?

d <- lapply(1:10, function(i) {model <- code
data.frame(model)})
df_total <- do.call(cbind, d)
  • you probably need to work with a list, or create values NA on your vector so that all vectors are the same size so you can make a cbind(). For an exact/better answer, please ask a reproducible question

1 answer

1

As pointed out by @Guilherme-Parreira in the comments, if its function returns vectors with different lengths, it is better to use a list. Since it did not post a reproducible code, I wrote an example function that returns a numerical vector of random length:

set.seed(462)

vetor.comp.aleat <- function(...) seq(sample(1:6, 1))

resultado <- lapply(1:3, vetor.comp.aleat)
names(resultado) <- LETTERS[1:length(resultado)]

resultado$C
#> [1] 1 2 3 4

data frame. is a special case of list where all elements are vectors of the same length. To convert the list to the results, you can first use lapply to change the lengths of all the elements of the list to the largest of them, using the operators in R to act as functions:

data.frame(lapply(resultado, "length<-", max(lengths(resultado))))
#>   A  B  C
#> 1 1  1  1
#> 2 2 NA  2
#> 3 3 NA  3
#> 4 4 NA  4
#> 5 5 NA NA

Browser other questions tagged

You are not signed in. Login or sign up in order to post.