How to convert a row into column names in R?

R ProgrammingServer Side ProgrammingProgramming

To convert a row into column names in R, we can follow the below steps −

  • First of all, create a data frame.

  • Convert the row into column names by using colnames function and subsetting the data frame.

Create the data frame

Let’s create a data frame as shown below −

 Live Demo

x<-c(round(rnorm(24),1),"x1")
y<-c(round(rnorm(24),1),"x2")
z<-c(round(rnorm(24),1),"x3")
df<-data.frame(x,y,z)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

Output

     x    y    z
1  -0.6  0.3  0.3
2   0    0.7 -1.6
3   0.5  0.4 1.5
4  -0.6 -0.5 0.2
5   0    0   0.7
6  -0.7  0.2 0.1
7  -0.1  0.2 -0.8
8  -0.9 -2.4  0.6
9   0    1.8  0.2
10 -2.8  0.7 1.3
11 -1.4 -0.6 -0.1
12 -1   -0.5    0
13 -1.7  0.3 0.2
14 -0.2 -0.4 0.8
15  1.2  0.5 -2.1
16  0.6 -1.1 0.7
17 -0.4  1.5 1.1
18  0    0 -0.4
19 -0.7 -0.9 1.2
20  1.1 -1.6 -0.8
21  0.3  1.8 1.6
22  2.1 -0.5 -0.5
23 -0.4 -0.3 0.2
24  0.2 -0.3 1.1
25  x1   x2  x3

Converting a row into column names

Using colnames function and subsetting with single square brackets to convert row 25 into column names −

 Live Demo

x<-c(round(rnorm(24),1),"x1")
y<-c(round(rnorm(24),1),"x2")
z<-c(round(rnorm(24),1),"x3")
df<-data.frame(x,y,z)
colnames(df)<-df[25,]
df<-df[-25,]
df

Output

    x1  x2    x3
1  -0.6  0.3  0.3
2   0    0.7 -1.6
3   0.5  0.4  1.5
4  -0.6 -0.5  0.2
5   0    0    0.7
6  -0.7  0.2  0.1
7  -0.1  0.2 -0.8
8  -0.9 -2.4  0.6
9   0    1.8  0.2
10 -2.8  0.7  1.3
11 -1.4 -0.6 -0.1
12 -1   -0.5  0
13 -1.7  0.3  0.2
14 -0.2 -0.4  0.8
15  1.2  0.5 -2.1
16  0.6 -1.1  0.7
17 -0.4  1.5  1.1
18  0    0    -0.4
19 -0.7 -0.9 1.2
20  1.1 -1.6 -0.8
21  0.3  1.8 1.6
22  2.1 -0.5 -0.5
23 -0.4 -0.3 0.2
24  0.2 -0.3 1.1
raja
Published on 11-Aug-2021 07:50:17
Advertisements