Home > Software design >  R: new column names in data frame and integration of the original columnames as part of the data
R: new column names in data frame and integration of the original columnames as part of the data

Time:09-21

I have the following dataframe:

df <-read.table(header=TRUE, text="1 0 0 1
                1 0 1 1
                1 0 0 0
                1 1 1 0
                2 1 0 0
                2 1 0 0
                2 1 1 0
                3 0 1 1
                3 0 0 1
                3 0 0 1")

I want to bring the column names as part of the data and create a column name such as V1, V2, V3 and V4:

df_new <-read.table(header=TRUE, text="V1 V2 V3 V4
                1 0 0 1
                1 0 1 1
                1 0 0 0
                1 1 1 0
                2 1 0 0
                2 1 0 0
                2 1 1 0
                3 0 1 1
                3 0 0 1
                3 0 0 1")

CodePudding user response:

Assuming in your actual case you have data like this -

df <-read.table(header=TRUE, text="1 0 0 1
                1 0 1 1
                1 0 0 0
                1 1 1 0
                2 1 0 0
                2 1 0 0
                2 1 1 0
                3 0 1 1
                3 0 0 1
                3 0 0 1", check.names = FALSE)

You can make the column names as first row by -

rbind(t(as.numeric(names(df))), setNames(df, paste0('V', seq_along(df))))

#   V1 V2 V3 V4
#1   1  0  0  1
#2   1  0  1  1
#3   1  0  0  0
#4   1  1  1  0
#5   2  1  0  0
#6   2  1  0  0
#7   2  1  1  0
#8   3  0  1  1
#9   3  0  0  1
#10  3  0  0  1
  • Related