-3

I have multiple data frames (namely Accident, Vehicles and Casualties) which are to be merged in a single data frame as Accidents. How do I find the factors of the combined data frame that is how to find factors of Accidents?

$ accident_severity           : char  "Serious" "Slight" "Slight" "Slight" ...
$ number_of_vehicles          : int  1 1 2 2 1 1 2 2 2 2 ...
$ number_of_casualties        : int  1 1 1 1 1 1 1 1 1 1 ...
$ date                        : char  "04/01/2005" "05/01/2005" "06/01/2005" "06/01/2005" ...
$ day_of_week                 : char  "Tuesday" "Wednesday" "Thursday" "Thursday" ...
$ time                        : char  "17:42" "17:36" "00:15" "00:15" ...
Artem
  • 3,304
  • 3
  • 18
  • 41
Nitisha
  • 11
  • 3
    Please edit your question to make it [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – NelsonGon Jun 14 '19 at 18:05

1 Answers1

0

You can convert columns of choice from character to factor using lapply function. See the code below for columns accident_severity and day_of_week conversion:

df <- data.frame(accident_severity= c("Serious", "Slight", "Slight", "Slight"),
                 number_of_vehicles =  c(1, 1, 2, 2),
                 number_of_casualties =  c(1,  1,  1,  1),
                 date =  c("04/01/2005", "05/01/2005", "06/01/2005", "06/01/2005"),
                 day_of_week =  c("Tuesday", "Wednesday", "Thursday", "Thursday"),
                 time = c("17:42", "17:36", "00:15", "00:15"),
                 stringsAsFactors = FALSE)
str(df)
# 'data.frame': 4 obs. of  6 variables:
#   $ accident_severity   : Factor w/ 2 levels "Serious","Slight": 1 2 2 2
# $ number_of_vehicles  : num  1 1 2 2
# $ number_of_casualties: num  1 1 1 1
# $ date                : chr  "04/01/2005" "05/01/2005" "06/01/2005" "06/01/2005"
# $ day_of_week         : Factor w/ 3 levels "Thursday","Tuesday",..: 2 3 1 1
# $ time                : chr  "17:42" "17:36" "00:15" "00:15"

df[c("accident_severity", "day_of_week")] <- lapply(df[c("accident_severity", "day_of_week")], factor)
str(df)
# 'data.frame': 4 obs. of  6 variables:
#   $ accident_severity   : Factor w/ 2 levels "Serious","Slight": 1 2 2 2
# $ number_of_vehicles  : num  1 1 2 2
# $ number_of_casualties: num  1 1 1 1
# $ date                : chr  "04/01/2005" "05/01/2005" "06/01/2005" "06/01/2005"
# $ day_of_week         : Factor w/ 3 levels "Thursday","Tuesday",..: 2 3 1 1
# $ time                : chr  "17:42" "17:36" "00:15" "00:15"

To find if a column names which are factors you can use is.factor function:

names(df)[unlist(lapply(df, is.factor))]
# [1] "accident_severity" "day_of_week"   
Artem
  • 3,304
  • 3
  • 18
  • 41