Hi. I am trying to fill a data frame with unequal size vectors. I would be OK with NAs, but the data frame is not reading all my elements.
df <- data.frame(matrix(ncol = 5, nrow=0)) x <- c(1,2,3) df <- rbind(df, x) y <- c(4,5,6,7) df <- rbind(df,y) z <- c(8,9,10,11,12) df <- rbind(df,z) df
X1 X2 X3 1 1 2 3 2 4 5 6 3 8 9 10
Try running these commands:
cbind(c(1,2,3), c(4,5,6,7), c(8,9,10,11,12)) rbind(c(1,2,3), c(4,5,6,7), c(8,9,10,11,12))
Then if you inspect the input, you will see what is called re-cycling.
Thanks Leon, I see what you are saying. Do you have a solution for my problem?
Before a solution can be offered I think you would need to specify the way you would have desired these entries to be bound together ?
Hi, I would a hope since I defined my df with 5 columns, it would look like the following. (I do understand recycling)
1 2 3 NA NA 4 5 6 7 NA 8 9 10 11 12
Make all vectors of the same length beforehand
library(purrr) x <- c(1,2,3) y <- c(4,5,6,7) z <- c(8,9,10,11,12) vector_list <- list(x, y, z) longest <- max(map_int(vector_list, length)) map_dfr(vector_list, ~ { length(.x) <- longest .x %>% set_names(paste0("X", 1:longest)) }) #> # A tibble: 3 × 5 #> X1 X2 X3 X4 X5 #> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 1 2 3 NA NA #> 2 4 5 6 7 NA #> 3 8 9 10 11 12
Created on 2021-10-01 by the reprex package (v2.0.1)
Well done, thank you.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.