# load the necessary libraries
library(wordcloud)
library(reshape2)
library(tidyverse)
library(tidyr)
library(tidytext)
library(dplyr)
Class Activity 13
Group Activity 1
a. Variance and Skewness
The variance of a random variable \(x\) is defined as:
\[\operatorname{Var}(x)=\frac{1}{n-1} \sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)^{2}\]
where \(x_i = (\sum_i^n x_i)/n\) is the sample mean. Also, the skewness of the random variable \(x\) is defined as:
\[\operatorname{Skew}(x)=\frac{\frac{1}{n-2}\left(\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)^{3}\right)}{\operatorname{Var}(x)^{3 /2}}\]
Please write functions to calculate the variance and skewness of \(\{12, 45, 54, 34, 56, 30, 67, \text{NA}\}\).
<- c(12, 45, 54, 34, 56, 30, 67, NA) x
Click for answer
# function to calculate the variance of a vector
<- function(x){
var <- na.omit(x) # omit NA values
x sum((x - mean(x)) ^ 2) / (length(x) - 1)
}
var(x)
[1] 346.619
# function to calculate the skewness of a vector
<- function(x) {
skewness <- na.omit(x) # omit NA values
x sum((x - mean(x)) ^ 3) /((length(x) - 2) * var(x) ^ (3 / 2))
}
skewness(x)
[1] -0.3930586
b. (Optional) Conditions and breaks
Create a function that iterates through a numeric vector and stops when it encounters the first negative number, returning the position of that negative number. If there are no negative numbers in the vector, the function should return a message stating that there are no negative numbers.
Click for answer
<- function(x) {
find_first_negative <- which(x < 0)
negative_positions
if (length(negative_positions) > 0) {
return(paste("The first negative number is at position", negative_positions[1]))
else {
} return("There are no negative numbers in the vector")
} }
<- c(5, 12, -7, 20, 15)
test_vector find_first_negative(test_vector)
[1] "The first negative number is at position 3"
Group Activity 2
<- read_csv("https://raw.githubusercontent.com/deepbas/statdatasets/main/musicreviews.csv") %>%
musical_instr_reviews rename(ratingOverall = overall)
glimpse(musical_instr_reviews)
Rows: 10,261
Columns: 3
$ reviewerName <chr> "cassandra tu \"Yeah, well, that's just like, u...", "Ja…
$ reviewText <chr> "not much to write about here but it does exactly what i…
$ ratingOverall <dbl> 5, 5, 5, 5, 5, 5, 5, 3, 5, 5, 5, 4, 3, 5, 5, 2, 4, 5, 5,…