I am running a query with a for-loop that creates vectors of different lengths. The code of the first vector is not necessarily the longest (I created the example so that the first column is the shortest and keeps getting longer). I want to somehow bind these vectors. I messed around a bit with this make-shift cbind.fill function, but did not get it to work (rowr::cbind.fill is no longer available in R 4.x.x).
The example code below does not run properly because runif(i) makes the vector longer for each subsequent loop. Please note that for the actual data I do not know which column is the longest. Checking this is possible but not preferred, although I can imagine that maybe just keeping the vectors until the loop is complete and binding them then would be faster.
Example code:
dat <- c(1,2,3)
dat <- as.data.frame(dat)
for (i in 1:5) {
temp <- runif(i)
dat <- cbind(dat, temp)
names(dat)[i+1] <- paste0("nr", i)
}
What is the fastest way turn the output vectors into a data.frame? I thought of putting them into a list of vectors first (but did not know how to do the naming in that case), or perhaps filling every vectors with NA's of the amount length(longest_vector)-length(vector[i]).
Desired output:
# A tibble: 8 x 6
dat nr1 nr2 nr3 nr4 nr5
<chr> <chr> <chr> <chr> <chr> <dbl>
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 NA 0.43526783056537444 0.25560407791435225 0.91653997616714789 0.62635622073335406 0.888
5 NA NA 0.56979342124862575 0.43296269966267631 0.46423817219260977 0.522
6 NA NA NA 0.89399553062032511 0.34917334540558442 0.745
7 NA NA NA NA 0.4131315834365703 0.0403
8 NA NA NA NA NA 0.564
desired_out <- structure(list(dat = c("1", "2", "3", "NA", "NA", "NA", "NA",
"NA"), nr1 = c("1", "2", "3", "0.43526783056537444", "NA", "NA",
"NA", "NA"), nr2 = c("1", "2", "3", "0.25560407791435225", "0.56979342124862575",
"NA", "NA", "NA"), nr3 = c("1", "2", "3", "0.91653997616714789",
"0.43296269966267631", "0.89399553062032511", "NA", "NA"), nr4 = c("1",
"2", "3", "0.62635622073335406", "0.46423817219260977", "0.34917334540558442",
"0.4131315834365703", "NA"), nr5 = c(1, 2, 3, 0.887930290142606,
0.522131799371126, 0.745103223905874, 0.0403367661303002, 0.563609740553749
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-8L))