Home > Blockchain >  Create dataframe from repeating vectors with increasing values in R
Create dataframe from repeating vectors with increasing values in R

Time:09-16

I'm struggling with something that might turn out to be super easy. What i'd like is some short and efficient code to create a dataframe where each column is made up of V1, V1 * 2, V1 * 3... and so on until a set number of columns is reached.

For example, if my V1 is this:

V1=rep(10000,1000)

I'd like a code to automatically generate additional columns such as V2 and V3

V2=V1*2
V3=V1*3

and bind them together in a dataframe to give

d=data.frame(V1,V2,V3)
d

Should this be done with a loop? Tried a bunch of things but am not the best at looping and at the moment I feel rather stuck.

Ideally I'd like my vector V1 to be:

V1=rep(10000,10973)

and to form a dataframe with 17 columns. Thanks!

CodePudding user response:

Use sapply to create multiple columns. Here, I am creating 17 columns where 1 to 10 are sequentially multiplied by 1, 2, ..., 17. Use as.data.frame to convert to data.frame object.

sapply(1:17, function(x) x * 1:10) |>
   as.data.frame()

output

   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17
1   1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17
2   2  4  6  8 10 12 14 16 18  20  22  24  26  28  30  32  34
3   3  6  9 12 15 18 21 24 27  30  33  36  39  42  45  48  51
4   4  8 12 16 20 24 28 32 36  40  44  48  52  56  60  64  68
5   5 10 15 20 25 30 35 40 45  50  55  60  65  70  75  80  85
6   6 12 18 24 30 36 42 48 54  60  66  72  78  84  90  96 102
7   7 14 21 28 35 42 49 56 63  70  77  84  91  98 105 112 119
8   8 16 24 32 40 48 56 64 72  80  88  96 104 112 120 128 136
9   9 18 27 36 45 54 63 72 81  90  99 108 117 126 135 144 153
10 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170

In your case, you would need:

sapply(1:17, function(x) x * rep(10000, 10973)) |>
  as.data.frame()

CodePudding user response:

We could use outer

as.data.frame( outer(1:10, 1:17))
  • Related