Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I just want to know that how can we convert a different length of List into a user-defined size data frame in R?

Let's assume, there is an input of the function is L (a list), N(a number).

Input example:

L <- list(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

N <- 6

The output should look like the below data frame:

    [,1] [,2] [,3]

[1,] 1    7    13

[2,] 2    8    14

[3,] 3    9    15

[4,] 4    10   NA

[5,] 5    11   NA

[6,] 6    12   NA

If you have any idea how to create this function, I would really appreciate it.

1 Answer

0 votes
by (108k points)

In R programming, you can use the matrix() and from that you can fill the missing values with NA using rep and cast it to a data.frame like:

as.data.frame(matrix(c(L, rep(NA, length(L) %% N)), N))

#  V1 V2 V3

#1  1  7 13

#2  2  8 14

#3  3  9 15

#4  4 10 NA

#5  5 11 NA

#6  6 12 NA

Browse Categories

...