I am getting different result while using str() and levels() commands
Title
Question
I am getting different results compared to those of tutorial video while using str(movies$mpaa_rating) and levels(movies$mpaa_rating) commands.
script:-
# Declare a variable to read and store moviesData
movies <- read.csv("moviesData.csv")
# View movies data frame
View(movies)
# Plot critics_score and audience_score
ggplot(data = movies,
mapping = aes(x = critics_score,
y = audience_score,
color = genre)) +
geom_point()
str(movies$mpaa_rating)
levels(movies$mpaa_rating)
console:-
> # Load ggplot2
> library(ggplot2)
> # Clear R workspace
> rm(list = ls() )
> # Declare a variable to read and store moviesData
> movies <- read.csv("moviesData.csv")
> # View movies data frame
> View(movies)
> # Plot critics_score and audience_score
> ggplot(data = movies,
+ mapping = aes(x = critics_score,
+ y = audience_sco .... [TRUNCATED]
> # Plot critics_score and audience_score
> ggplot(data = movies,
+ mapping = aes(x = critics_score,
+ y = audience_score,
+ color = genre)) +
+ geom_point()
> str(movies$mpaa_rating)
chr [1:600] "R" "PG-13" "R" "PG" "R" ...
> levels(movies$mpaa_rating)
NULL
> str(movies$mpaa_rating)
chr [1:600] "R" "PG-13" "R" "PG" "R" ...
> levels(movies$mpaa_rating)
NULL
R Aesthetic-Mapping-in-ggplot2 04-05 min 40-50 sec
Answers:
You need to convert the data into a factor by executing the code shown below -
movies$mpaa_rating <- as.factor(movies$mpaa_rating)
Then you will get the desired results -
> str(movies$mpaa_rating)
Factor w/ 6 levels "G","NC-17","PG",..: 5 4 5 3 5 6 4 5 6 6 ...
> levels(movies$mpaa_rating)
[1] "G" "NC-17" "PG" "PG-13" "R" "Unrated"
Factor w/ 6 levels "G","NC-17","PG",..: 5 4 5 3 5 6 4 5 6 6 ...
> levels(movies$mpaa_rating)
[1] "G" "NC-17" "PG" "PG-13" "R" "Unrated"
Login to add comment