Accessing elements of a Factor in R
Like we access elements of a vector, the same way we access the elements of a factor. If gender is a factor then gender[i] would mean accessing an ith element in the factor.
Example
R
gender <- factor ( c ( "female" , "male" , "male" , "female" )); gender[3] |
Output
[1] male Levels: female male
More than one element can be accessed at a time.
Example
R
gender <- factor ( c ( "female" , "male" , "male" , "female" )); gender[ c (2, 4)] |
Output
[1] male female Levels: female male
Subtract one element at a time.
Example
R
gender <- factor ( c ( "female" , "male" , "male" , "female" )); gender[-3] |
Output
[1] female male female Levels: female male
- First, we create a factor vector gender with four elements: “female”, “male”, “male”, and “female”.
- Then, we use the square brackets [-3] to subset the vector and remove the third element, which is “male”.
- The output is the remaining elements of the gender vector, which are “female”, “male”, and “female”. The output also shows the levels of the factor, which are “female” and “male”.
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