Home > Software engineering >  Replicate column based on colnames in R
Replicate column based on colnames in R

Time:07-31

I have a data frame in R, namely data as follows:

set.seed(123)
    data <- as.data.frame(matrix(rnorm(12 * 4, mean = 0, sd = 1), 12, 4))
    colnames(data) <-
      c("A", "B", "C", "D")

which results in:

> data
             A          B          C           D
1  -0.56047565  0.4007715 -0.6250393  0.55391765
2  -0.23017749  0.1106827 -1.6866933 -0.06191171
3   1.55870831 -0.5558411  0.8377870 -0.30596266
4   0.07050839  1.7869131  0.1533731 -0.38047100
5   0.12928774  0.4978505 -1.1381369 -0.69470698
6   1.71506499 -1.9666172  1.2538149 -0.20791728
7   0.46091621  0.7013559  0.4264642 -1.26539635
8  -1.26506123 -0.4727914 -0.2950715  2.16895597
9  -0.68685285 -1.0678237  0.8951257  1.20796200
10 -0.44566197 -0.2179749  0.8781335 -1.12310858
11  1.22408180 -1.0260044  0.8215811 -0.40288484
12  0.35981383 -0.7288912  0.6886403 -0.46665535

How can I add a column (first column) in data and create datanew, that contains the colnames(data) in replication form in the first column? The final result I want to be the following

   > datanew
                 A          B          C           D
  A    -0.56047565  0.4007715 -0.6250393  0.55391765
  B    -0.23017749  0.1106827 -1.6866933 -0.06191171
  C     1.55870831 -0.5558411  0.8377870 -0.30596266
  D     0.07050839  1.7869131  0.1533731 -0.38047100
  A     0.12928774  0.4978505 -1.1381369 -0.69470698
  B     1.71506499 -1.9666172  1.2538149 -0.20791728
  C     0.46091621  0.7013559  0.4264642 -1.26539635
  D    -1.26506123 -0.4727914 -0.2950715  2.16895597
  A    -0.68685285 -1.0678237  0.8951257  1.20796200
  B    -0.44566197 -0.2179749  0.8781335 -1.12310858
  C     1.22408180 -1.0260044  0.8215811 -0.40288484
  D     0.35981383 -0.7288912  0.6886403 -0.46665535

How can I do that in R? Can someone help me?

CodePudding user response:

This is against naming conventions!!!

library(dplyr)

data %>% 
  mutate(` `= rep_len(colnames(data), length.out=nrow(data)), .before=1)
               A          B          C           D
1  A -0.56047565  0.4007715 -0.6250393  0.55391765
2  B -0.23017749  0.1106827 -1.6866933 -0.06191171
3  C  1.55870831 -0.5558411  0.8377870 -0.30596266
4  D  0.07050839  1.7869131  0.1533731 -0.38047100
5  A  0.12928774  0.4978505 -1.1381369 -0.69470698
6  B  1.71506499 -1.9666172  1.2538149 -0.20791728
7  C  0.46091621  0.7013559  0.4264642 -1.26539635
8  D -1.26506123 -0.4727914 -0.2950715  2.16895597
9  A -0.68685285 -1.0678237  0.8951257  1.20796200
10 B -0.44566197 -0.2179749  0.8781335 -1.12310858
11 C  1.22408180 -1.0260044  0.8215811 -0.40288484
12 D  0.35981383 -0.7288912  0.6886403 -0.46665535
  • Related