Data Frame with Unequal Lengths Columns in R (Example Code)
In this tutorial, I’ll show how to create a data frame with columns that have an unequal length in the R programming language.
Creation of Exemplifying Data
vec1 <- 10:13 # Construct example vectors in R vec2 <- letters[10:5] vec3 <- 1:10 |
vec1 <- 10:13 # Construct example vectors in R vec2 <- letters[10:5] vec3 <- 1:10
Example: Merge Vectors with Unequal Lengths Using length() Function
maximum_length <- max(c(length(vec1), # Get length of longest variable length(vec2), length(vec3))) |
maximum_length <- max(c(length(vec1), # Get length of longest variable length(vec2), length(vec3)))
df <- data.frame( # Construct data frame with NA values vec1 = c(vec1, rep(NA, maximum_length - length(vec1))), vec2 = c(vec2, rep(NA, maximum_length - length(vec2))), vec3 = c(vec3, rep(NA, maximum_length - length(vec3)))) df # Display data frame in RStudio console # vec1 vec2 vec3 # 1 10 j 1 # 2 11 i 2 # 3 12 h 3 # 4 13 g 4 # 5 NA f 5 # 6 NA e 6 # 7 NA <NA> 7 # 8 NA <NA> 8 # 9 NA <NA> 9 # 10 NA <NA> 10 |
df <- data.frame( # Construct data frame with NA values vec1 = c(vec1, rep(NA, maximum_length - length(vec1))), vec2 = c(vec2, rep(NA, maximum_length - length(vec2))), vec3 = c(vec3, rep(NA, maximum_length - length(vec3)))) df # Display data frame in RStudio console # vec1 vec2 vec3 # 1 10 j 1 # 2 11 i 2 # 3 12 h 3 # 4 13 g 4 # 5 NA f 5 # 6 NA e 6 # 7 NA <NA> 7 # 8 NA <NA> 8 # 9 NA <NA> 9 # 10 NA <NA> 10
Further Resources & Related Articles
Here, you may find some additional resources on topics such as merging, missing data, and indices: