Modification of a Factor in R
After a factor is formed, its components can be modified but the new values which need to be assigned must be at the predefined level.
Example
R
gender <- factor ( c ( "female" , "male" , "male" , "female" )); gender[2]<- "female" gender |
Output
[1] female female male female Levels: female male
For selecting all the elements of the factor gender except ith element, gender[-i] should be used. So if you want to modify a factor and add value out of predefined levels, then first modify levels.
Example
R
gender <- factor ( c ( "female" , "male" , "male" , "female" )); # add new level levels (gender) <- c ( levels (gender), "other" ) gender[3] <- "other" gender |
Output
[1] female male other female Levels: female male other
R Factors
Factors in R Programming Language are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels.
They can be stored as integers with a corresponding label to every unique integer. The R factors may look similar to character vectors, they are integers and care must be taken while using them as strings. The R factor accepts only a restricted number of distinct values. For example, a data field such as gender may contain values only from female, male, or transgender.
In the above example, all the possible cases are known beforehand and are predefined. These distinct values are known as levels. After a factor is created it only consists of levels that are by default sorted alphabetically.
Contact Us