How to find the number of levels of a factor column in R?
To find the number of levels in R for a factor column, we can use the length function with the unique function. For example, if we have a data frame named df with a factor column X, we can use the following command to find the number of levels in the factor column −
length (unique(df$X))
Example
Consider the following dataframe -
x1<-sample(c( "A" , "B" , "C" ), 20 ,replace= TRUE ) y1<-sample( 0 : 9 , 20 ,replace= TRUE ) df1<-data.frame(x1,y1) df1
output result
x1 y1 1 C 8 2 B 9 3 B 2 4 A 7 5 A 8 6 C 4 7 B 0 8 C 3 9 B 3 10 A 5 11 A 8 12 B 0 13 A 6 14 C 2 15 A 4 16 B 7 17 A 9 18 B 1 19 B 3 20 A 5
Find the number of levels in column x1 -
Example
length (unique(df1$x1))
output result
[ 1 ] 3
Example
x2<-sample(c( "id1" , "id2" , "id3" , "id4" ), 20 ,replace= TRUE ) y2<-rnorm( 20 , 1 , 0.05 ) df2<-data.frame(x2,y2) df2
output result
x2 y2 1 id2 1.0582275 2 id4 0.8763659 3 id4 1.0091340 4 id1 1.0087233 5 id1 1.0022543 6 id3 0.9682852 7 id3 0.9458475 8 id2 1.0329383 9 id3 0.9890525 10 id1 0.9814830 11 id4 0.9732973 12 id1 1.0644264 13 id3 0.9328492 14 id1 0.9064330 15 id2 0.9781466 16 id2 0.9633579 17 id1 0.9985626 18 id4 1.0428324 19 id4 1.0047497 20 id4 0.9717654
Find the number of levels in column x2 -
Example
length (unique(df2$x2))
output result
[ 1 ] 4
0 Comments