R How to Use stringsAsFactors in the data.frame Function (2 Examples)
This tutorial explains how to apply the stringsAsFactors argument of the data.frame function in the R programming language.
Example 1: Setting stringsAsFactors to be Equal to TRUE
df_A <- data.frame(x = 15:20, # Factor variables y = LETTERS[3:8], z = letters[19:24], stringsAsFactors = TRUE) df_A # Displaying data.frame in RStudio # x y z # 1 15 C s # 2 16 D t # 3 17 E u # 4 18 F v # 5 19 G w # 6 20 H x |
df_A <- data.frame(x = 15:20, # Factor variables y = LETTERS[3:8], z = letters[19:24], stringsAsFactors = TRUE) df_A # Displaying data.frame in RStudio # x y z # 1 15 C s # 2 16 D t # 3 17 E u # 4 18 F v # 5 19 G w # 6 20 H x
sapply(df_A, class) # Data type of columns # x y z # "integer" "factor" "factor" |
sapply(df_A, class) # Data type of columns # x y z # "integer" "factor" "factor"
Example 2: Setting stringsAsFactors to be Equal to FALSE
df_B <- data.frame(x = 15:20, # Character variables y = LETTERS[3:8], z = letters[19:24], stringsAsFactors = FALSE) df_B # Displaying data.frame in RStudio # x y z # 1 15 C s # 2 16 D t # 3 17 E u # 4 18 F v # 5 19 G w # 6 20 H x |
df_B <- data.frame(x = 15:20, # Character variables y = LETTERS[3:8], z = letters[19:24], stringsAsFactors = FALSE) df_B # Displaying data.frame in RStudio # x y z # 1 15 C s # 2 16 D t # 3 17 E u # 4 18 F v # 5 19 G w # 6 20 H x
sapply(df_B, class) # Data type of columns # x y z # "integer" "character" "character" |
sapply(df_B, class) # Data type of columns # x y z # "integer" "character" "character"