- Convert single column to factor
- Convert multiple columns to factor
Following data frame, df, is used in the code sample below:
param_a param_b param_c diagnosis param_d 1 23 0.61 10452 positive y 2 18 0.85 9876 positive n 3 22 0.32 6534 negative y 4 37 0.56 8743 positive y 5 15 0.44 9876 negative n 6 25 0.13 4321 negative n 7 55 0.51 7685 positive y
In above data frame, both diagnosis and param_d are character vectors. One could quickly check classes of all columns using following command:
Convert Single Column to Factor
Following is demonstrated the code samples along with help text. Pay attention that one could use lapply method to change single column to factor. However, it does throw warning message.
# Invoke as.factor method on dataframe$columnName df$param_d <- as.factor(df$param_d) # Invoke as.factor method on columns represented array notation df[, 'param_d'] <- as.factor( df[, 'param_d'] ) # Use lapply method; Both of below makes param_d column as factor df[, 'param_d'] <- lapply(df[, 'param_d'], factor) df[, c("param_d")] <- lapply(df[, c("param_d")], factor)
Convert Multiple Columns to Factor
Use lapply method to change columns to factor.
df[, c("param_d", "diagnosis")] <- lapply(df[, c("param_d", "diagnosis")], factor)
He has also authored the book, Building Web Apps with Spring 5 and Angular.
Latest posts by Ajitesh Kumar (see all)
- Quantum Computing Interview Questions and Answers – Set 1 - December 12, 2017
- Hyperledger Interview Questions and Answers – Set 1 - December 12, 2017
- List of Hyperledger Tools & Frameworks for Blockchain Apps - December 12, 2017