covnert a dataframe variable from character to factor in r

To convert a variable in a dataframe from character to factor, you can use the factor() function in R.

main.r
# example dataframe
mydf <- data.frame(
  name = c("John", "Sarah", "Michael", "Michelle"),
  gender = c("Male", "Female", "Male", "Female"),
  age = c(24, 32, 28, 42),
  stringsAsFactors = FALSE
)
# check the structure of the dataframe, gender variable is character
str(mydf)

# convert gender variable from character to factor
mydf$gender <- factor(mydf$gender)

# check the structure of the dataframe again, gender variable is now a factor
str(mydf)
453 chars
16 lines

In the above example, we first created a dataframe with three variables: name, gender and age, with gender as a character variable. We then used the factor() function to convert the gender variable to a factor variable. We checked the structure of the dataframe before and after the conversion to verify that the conversion was successful.

gistlibby LogSnag