Convert Character to Factor in R (3 Examples) | Vector, Data Column & Variables | as.factor Function
20.7 هزار بار بازدید -
5 سال پیش
-
How to convert character vectors,
How to convert character vectors, data frame columns and variables to the factor class in the R programming language. More info: https://statisticsglobe.com/convert-c...
R programming code:
##### Example 1
vec <- c("A", "B", "A", "D", "C", "B") # Create example vector
class(vec) # Check class of vector
vec_updated <- as.factor(vec) # Convert character vector to factor
class(vec_updated)
##### Example 2
data <- data.frame(x1 = 1:5, # Create example data frame
x2 = letters[1:5],
x3 = c(4, 1, 5, 3, 1),
x4 = c("Male", "Female", "Male", "Male", "Female"),
stringsAsFactors = FALSE)
data # Print example data frame
data2 <- data # Replicate example data frame
class(data2$x2) # Check class of second column
data2$x2 <- as.factor(data2$x2) # Convert character column to factor
class(data2$x2) # Check class of second column
##### Example 3
data3 <- data # Replicate example data frame
str(data3) # Check class of all columns
data3 <- as.data.frame(unclass(data3), # Convert all columns to factor
stringsAsFactors = TRUE)
str(data3) # Check class of all columns
R programming code:
##### Example 1
vec <- c("A", "B", "A", "D", "C", "B") # Create example vector
class(vec) # Check class of vector
vec_updated <- as.factor(vec) # Convert character vector to factor
class(vec_updated)
##### Example 2
data <- data.frame(x1 = 1:5, # Create example data frame
x2 = letters[1:5],
x3 = c(4, 1, 5, 3, 1),
x4 = c("Male", "Female", "Male", "Male", "Female"),
stringsAsFactors = FALSE)
data # Print example data frame
data2 <- data # Replicate example data frame
class(data2$x2) # Check class of second column
data2$x2 <- as.factor(data2$x2) # Convert character column to factor
class(data2$x2) # Check class of second column
##### Example 3
data3 <- data # Replicate example data frame
str(data3) # Check class of all columns
data3 <- as.data.frame(unclass(data3), # Convert all columns to factor
stringsAsFactors = TRUE)
str(data3) # Check class of all columns
5 سال پیش
در تاریخ 1398/09/25 منتشر شده
است.
20,759
بـار بازدید شده