How to remove column names from an R data frame?

R ProgrammingServer Side ProgrammingProgramming

There are situations when we might want to remove column names such as we want to manually replace the existing column names by new names or we simply don’t want to use them if we are very much familiar with the column characteristics. To remove the columns names we can simply set them to NULL as shown in the below examples.

Example1

Consider the below data frame −

 Live Demo

set.seed(357)
x1<−LETTERS[1:20]
x2<−rnorm(20)
x3<−rpois(20,5)
df1<−data.frame(x1,x2,x3)
df1

Output

   x1    x2     x3
1 A −1.24111731  3
2 B −0.58320499  1
3 C 0.39474705   6
4 D 1.50421107   4
5 E 0.76679974   5
6 F 0.31746044   4
7 G −0.09997594  5
8 H 0.22703071   9
9 I −0.46901506  2
10 J 0.47652129  5
11 K −0.91164798 7
12 L −0.34177516 4
13 M 0.54674134  4
14 N −0.32720797 4
15 O 0.04108975  3
16 P −0.27603366 2
17 Q −0.59349654 2
18 R 0.17646182  6
19 S 0.50575975  4
20 T 1.00851578  3

Removing column names from df1 −

Example

names(df1)<−NULL
df1

Output

1 A −1.24111731  3
2 B −0.58320499  1
3 C 0.39474705   6
4 D 1.50421107   4
5 E 0.76679974   5
6 F 0.31746044   4
7 G −0.09997594  5
8 H 0.22703071   9
9 I −0.46901506  2
10 J 0.47652129  5
11 K −0.91164798 7
12 L −0.34177516 4
13 M 0.54674134  4
14 N −0.32720797 4
15 O 0.04108975  3
16 P −0.27603366 2
17 Q −0.59349654 2
18 R 0.17646182  6
19 S 0.50575975  4
20 T 1.00851578  3

Example2

 Live Demo

y1<−rexp(20,2.24)
y2<−runif(20,2,10)
y3<−rpois(20,2)
df2<−data.frame(y1,y2,y3)
df2

Output

   y1       y2         y3
1 0.407887709  2.213538  1
2 1.740076315  8.314833  3
3 0.192889321  2.085092  1
4 0.166686518  2.295179  3
5 0.057761320  3.117768  5
6 0.001199064  8.917747  3
7 0.212810013  5.560138  1
8 0.295809473  6.418326  0
9 0.198128409  6.662312  3
10 0.711248734 4.899675  2
11 0.228512534 5.439995  1
12 0.614415810 7.231990  2
13 0.552638453 6.999130  3
14 1.181955638 2.650087  3
15 0.094478314 4.154438  4
16 0.114416419 2.687630  3
17 0.521020383 4.552469  2
18 0.145134708 3.100630  1
19 0.189475950 3.741155  1
20 0.055434073 7.268179 3

Removing column names from df2 −

Example

names(df2)<−NULL
df2

Output

1 0.407887709 2.213538 1
2 1.740076315 8.314833 3
3 0.192889321 2.085092 1
4 0.166686518 2.295179 3
5 0.057761320 3.117768 5
6 0.001199064 8.917747 3
7 0.212810013 5.560138 1
8 0.295809473 6.418326 0
9 0.198128409 6.662312 3
10 0.711248734 4.899675 2
11 0.228512534 5.439995 1
12 0.614415810 7.231990 2
13 0.552638453 6.999130 3
14 1.181955638 2.650087 3
15 0.094478314 4.154438 4
16 0.114416419 2.687630 3
17 0.521020383 4.552469 2
18 0.145134708 3.100630 1
19 0.189475950 3.741155 1
20 0.055434073 7.268179 3
raja
Published on 05-Feb-2021 08:23:46
Advertisements