Search code examples
rdataframelist

R convert list output from loop to data frame


I have a series of numbers.

n <- c(10, 5, 35, 16, 2)
n <- as.data.frame(n)

I ran these numbers through a loop that randomly samples from -18 to 18 the number of times of the values, e.g., 10, 5.

p <- list()
for(i in 1:nrow(n)) {
  p[[i]] <- sample(-18:18, n$n[i], replace = TRUE)
}

The output looks like this:

[[1]]
[1] 6 1

[[2]]
[1]  4  1 12 -8 -9

[[3]]
[1] -13 -18  18

[[4]]
[1] 17 -4  9 17

[[5]]
[1] -2 18

How do I convert this to a data frame that also has an ID variable corresponding to the order? I want the output to look like this:

CT  ID
6   1 
1   1
4   2
1   2
12  2
-8  2
-9  2
-13 3
-18 3
18  3
17  4
-4  4
9   4
17  4
-2  5
18  5

My actual data has around 300 variable cells/lists that need to be converted. I tried creating another loop, but keep encountering syntax errors.


Solution

  • If one call to sample (i.e. sum(n)) is not what you want, we can Vectorise sample() like

    set.seed(1)
    n = c(10, 5, 35, 16, 2)
    data.frame(ID=rep(seq(n), n), 
               CT=unlist(Vectorize(sample, "size")(-18:18, n, TRUE)))
    

    giving

       ID  CT
    1   1 -15
    2   1 -18
    3   1  15
    4   1   4
    5   1  -5
    6   1  -1
    7   1  14
    8   1   2
    9   1   2
    10  1  -9
    11  2 -12
    12  2 -10
    13  2  -4
    14  2   2
    15  2  18
    16  3   6
    17  3  18
    18  3  18
    19  3  15
    20  3   6
    21  3  -4
    22  3  14
    23  3   1
    24  3  16
    25  3 -13
    26  3  -9
    27  3   1
    28  3   9
    29  3   1
    30  3   4
    31  3 -13
    32  3   6
    33  3 -13
    34  3 -13
    35  3   5
    36  3  13
    37  3  -5
    38  3 -17
    39  3  -1
    40  3   3
    41  3  -5
    42  3 -18
    43  3 -13
    44  3   4
    45  3 -13
    46  3  -8
    47  3  -2
    48  3  17
    49  3  -6
    50  3   6
    51  4   6
    52  4   4
    53  4   1
    54  4  10
    55  4  -6
    56  4   3
    57  4  10
    58  4   9
    59  4  14
    60  4   2
    61  4  12
    62  4  -2
    63  4 -10
    64  4   4
    65  4   0
    66  4   7
    67  5  11
    68  5  13