Open In App

Create Dataframe of Unequal Length in R

In this article, we will be looking at the approach to create a data frame of unequal length using different functions in R Programming language.

To create a data frame of unequal length, we add the NA value at the end of the columns which are smaller in the lengths and makes them equal to the column which has the maximum length among all and with this process all the length becomes equal and the user is able to process operations on that data frame in R language. 



rep() function is used to replicate the values in x. Here, this will be used to replicate NA value of the end of the columns of the data frames.

Syntax: rep(x, …)



Parameters:

  • x:-a vector or a factor or a POSIXct or POSIXlt or Date object.
  • …:-further arguments to be passed to or from other methods

Example 1:




# Creating variable
x=c(1,2,3,4,5)
y=c(1,2,3)
  
# Finding maximum length
max_ln <- max(c(length(x), length(y)))
gfg_data<- data.frame(col1 = c(x,rep(NA, max_ln - length(x))),
                      col2 = c(y,rep(NA, max_ln - length(y))))
gfg_data
is.data.frame((gfg_data))

Output:

Example 2:




# Creating variable
a=c('a','b','c','d')
b=c('g','e','e','k','s')
c=c('f','o','r')
d=c('g','e','e','k','s')
  
# Finding maximum length
max_ln1 <- max(c(length(a), length(b)))
max_ln2 <- max(c(length(c), length(d)))
max_ln<-max(max_ln2,max_ln1)
gfg_data<- data.frame(col1 = c(a,rep(NA, max_ln - length(a))),
                      col2 = c(b,rep(NA, max_ln - length(b))),
                      col3 = c(c,rep(NA, max_ln - length(c))),
                      col4 = c(d,rep(NA, max_ln - length(d))))
  
gfg_data
is.data.frame((gfg_data))

Output:


Article Tags :