How to extract only factor columns name from an R data frame?


To extract only factor column names from an R data frame, we can use names function with Filter by selecting only factor columns using as.factor. For example, if we have a data frame called df that contains some factor columns then the extraction of names of these factor columns can be done by using names(Filter(is.factor,df)).

Consider the below data frame −

Example

 Live Demo

x1<-factor(sample(c("Male","Female"),20,replace=TRUE))
x2<-rpois(20,5)
df1<-data.frame(x1,x2)
df1

Output

    x1    x2
1 Female  4
2   Male  7
3   Male  9
4 Female  3
5   Male  10
6 Female  4
7 Female  2
8 Female  1
9 Female  6
10 Female 7
11 Female 5
12   Male 5
13   Male 6
14 Female 4
15   Male 7
16   Male 3
17   Male 2
18   Male 4
19   Male 9
20 Female 6

Extracting names of factor column df1 −

names(Filter(is.factor,df1))

[1] "x1"

Example

 Live Demo

y1<-rnorm(20)
y2<-rnorm(20,524,32.14)
y3<-factor(sample(c("Hot","Cold"),20,replace=TRUE))
df2<-data.frame(y1,y2,y3)
df2

Output

      y1            y2        y3
1   1.14683171   494.4162    Hot
2   0.91868842   580.5509    Hot
3   -0.17573235  534.0396    Cold
4   -0.02975191  488.0148    Cold
5   -0.26811263  492.4373    Hot
6   0.66937789   458.3491    Hot
7   0.47413241   488.5430    Cold
8  0.28988748   495.5700     Hot
9  -0.29068059   509.0902    Cold
10  -0.88108903  484.8437    Hot
11  -0.33612356  535.9354    Hot
12  0.40103781   510.7365    Hot
13  -0.92194471  521.3352    Hot
14  1.25918659   520.2907    Hot
15  -1.22533456  443.9293    Cold
16  1.81055353   494.4451    Hot
17  0.43367087   530.8559    Cold
18  1.63945140   489.3504    Cold
19  -1.55321040   541.3161   Cold
20  -1.02131445   510.2723   Cold

Extracting names of factor column df2 −

names(Filter(is.factor,df2))

[1] "y3"

Updated on: 06-Feb-2021

973 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements