How to add columns dynamically in a dataframe based on numerical values sequences from another column? I want to add n
columns into a dataframe based on values from another column. What do I have and what do I want to have:
I have this:
head(df)
x y
[1] 1 ola
[2] 2 ola
[3] 3 ola
[4] 5 ola
[5] 4 ola
[6] 2 ola
[7] 3 ola
[8] 1 ola
[9] 5 ola
[10] 4 ola
[11] 2 ola
[12] 3 ola
[13] 5 ola
[14] 4 ola
[15] 1 ola
[16] 2 ola
[17] 3 ola
[18] 5 ola
[19] 4 ola
[20] 1 ola
[21] 3 ola
[22] 5 ola
[23] 2 ola
[24] 1 ola
[25] 4 ola
[26] 2 ola
In my case, I have a dataframe with 18
columns and each columns has 3305708
rows. So, what do I want to do? I want to dynamically add columns based on column values x
. That is, in this case, add more 5
columns with values 0
and 1
. Like this:
head(df)
x y x_1 x_2 x_3 ...
[1] 1 ola 1 0 0 ...
[2] 2 ola 0 1 0 ...
[3] 3 ola 0 0 1 ...
[4] 5 ola 0 0 0 ...
[5] 4 ola 0 0 0 ...
[6] 2 ola 0 1 0 ...
[7] 5 ola 0 0 0 ...
[8] 1 ola 1 0 0 ...
[9] 5 ola 0 0 0 ...
[10] 4 ola 0 0 0 ...
[11] 2 ola 0 1 0 ...
[12] 3 ola 0 0 1 ...
[13] 5 ola 0 0 0 ...
[14] 4 ola 0 0 0 ...
[15] 1 ola 1 0 0 ...
[16] 2 ola 0 1 0 ...
[17] 3 ola 0 0 1 ...
[18] 5 ola 0 0 0 ...
[19] 4 ola 0 0 0 ...
[20] 1 ola 1 0 0 ...
[21] 3 ola 0 0 1 ...
[22] 5 ola 0 0 0 ...
[23] 2 ola 0 1 0 ...
[24] 1 ola 1 0 0 ...
[25] 4 ola 0 0 0 ...
[26] 2 ola 0 1 0 ...
How can I do this dynamically? In this case I have just 5
values, but in my case I have columns that has 45
values and I have to add columns the same way I did here. How can I do this?