unfactor: Convert factor into appropriate class

View source: R/unfactor.R

unfactorR Documentation

Convert factor into appropriate class

Description

This function gets a factor vector, data.frame or matrix (that contains factor columns), detects the real class of the values and convert factor to the real class.

Usage

    unfactor(obj, auto_class_conversion = TRUE, verbose = FALSE)

Arguments

obj

The factor vector, data.frame or matrix. (Mandatory)

auto_class_conversion

Whether or not the function should automatically convert numbers to numeric. If set to FALSE, it will return all columns as class characters. Default is TRUE. (Optional)

verbose

Whether or not the function should be verbose, meaning it should message user about the details of operation. Default is FALSE. (Optional)

Details

This function turns factors to their real values. When a data.frame is given, the function detects factor columns and unfactor them, so you can give the whole data.frame and the function takes care of the rest. The values' real class detection mechanism is in a way that if everything in that column or vector are numbers and a decimal character, it change it to numeric otherwise it will be changed to character vector. This functionality can be turned off by setting the 'auto_class_conversion' argument to FALSE

Value

In case of providing a vector as an input, a character vector or numeric vector. This depends on the type of values the input variable contains. Check the details section for detailed information. In case of providing a data.frame, the same data.frame will be returned but with converted columns. In case there is nothing to get converted from factors, the function peacefully exits. You can get the details of the steps in form of message if you set the 'verbose' argument to TRUE.

Note

In case you have any issues with the function, please report to: https://bitbucket.org/mehrad_mahmoudian/varhandle/issues

Author(s)

Mehrad Mahmoudian

See Also

as.character, as.numeric

Examples

    # load a dataframe (from base package)
    data(iris)
    
    # see the actual values of the categorical column
    class(iris$Species)
    
    # use vector as input
    species <- unfactor(iris$Species)
    # check the class
    class(species)
    
    # use data.frame as input
    my_iris <- data.frame(Sepal.Length=factor(iris$Sepal.Length), sample_id=factor(1:nrow(iris)))
    my_iris <- unfactor(my_iris)
    # check the class
    class(my_iris)
    class(my_iris$Sepal.Length)
    class(my_iris$sample_id)

varhandle documentation built on Oct. 1, 2023, 1:08 a.m.