1. Factor function
#Function factor can encode a vector into a factor, and its general form is:#factor(x,levels=sort(unique(x),=TRUE),labels,exculde=NA,order=FALSE) # where x is a vector and levels is a level. You can specify discrete values by yourself. If not specified, it is represented by different values of x. Labels can be used to specify labels for each level.#When not specified, use the corresponding string of each discrete value sex<-c("M","F","M","M","F") factor(sex) #Use to determine whether the object is a factor type(sex) #Use to convert an object to a factor type<-(sex) #Use levels to get the level in the factorlevels() # [1] "F" "M"
2. Tapply function
#function taply()#When we know the gender of 5 people and the height of 5 people, we can calculate the average height of each genderheight<-c(170,175,180,165,168) tapply(height,,mean) # F M # 171.5000 171.6667 #tapply The usage format istapply(x,index,fun) inxFor the object,indexFor andxFactor types with the same number,funThe specified method
3. gl() function
#gl() function#gl function can generate factors quickly, and its basic usage is: gl(n,k,length=n*k,labels=1:n,order=false) gl(3,5) # [1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 # Levels: 1 2 3 gl(3,1,15) # [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 # Levels: 1 2 3
Supplementary: The problem of converting factor into numeric in R language
I have always thought that as long as it is a number, no matter what type it is, it can be converted into a corresponding numeric type number through the() function, for example
x<-"123", x is type character, and (x) is type 123 of numeric. But the factor type is different.
a<-factor(c(100,200,300,301,302,400,10)), their values are 100 200 300 301 302 400 10, but the corresponding value of (a) is not 100 200 300 301 302 400 10, but 2 3 4 5 6 7 1. The rules for converting factor into numeric types are as follows:
There are n numbers in total, so the converted number will take the value in 1-n, the smallest number will take one, the smallest number will take two, and so on.
So how do you make the numerical type convert the corresponding numerical type in the factor type?
((factorname)) (levels(factorname)[factorname])
All the above codes can implement the corresponding numerical type conversion of the numerical type in the factor type. The idea is to convert it into a character type first and then to a numerical type.