DS4PS / cpp-526-spr-2021

Course shell for Foundations of Data Science I
https://ds4ps.org/cpp-526-spr-2021/
MIT License
1 stars 2 forks source link

Lab 5 - Part 1- Q3 #12

Open AhmedRashwanASU opened 3 years ago

AhmedRashwanASU commented 3 years ago

wanted to know if I'm following the correct way of solving this question using the below equation , the answer was 0 while using the OR relation as below

3. Harmful Monday Accidents (%)

Question: What proportion of accidents on Mondays result in harm??

Note: "Harm" is defined as any accident that causes at least one injury or fatality, a.k.a. a "casualty".



harm_monday_Accidents <-mean(dat$day == "Mon" & (dat$Totalinjuries > 0 || dat$Totalfatalities > 0) , na.rm = TRUE)

prop_harm_monday_Accidents<-harm_monday_Accidents*100

prop_harm_monday_Accidents<- round(prop_harm_monday_Accidents, 2)       #  Round with 'round()'

paste(prop_harm_monday_Accidents, "%")

= 0

jamisoncrawford commented 3 years ago

This looks like a very straightforward and concise way to get the answer - 🔥 🔥 🔥

Check your "or" operator (|). It looks ike you used it twice. Fun fact, that's essentially function paste() in SQL (or CONCAT). But in R, alas, probably not what you want!

Edit: The || is actually "or" but non-vectorized. In other words, it only evaluates the first TRUE or FALSE in an array of different conditional or relational statements. The single | evaluates all the statements in an array and may return multiple logical values!

AhmedRashwanASU commented 3 years ago

Thank you! @jamisoncrawford

lecy commented 3 years ago

A general FYI:

I suspect you've done some coding before because some other languages will use double operators by default. For example && or ||.

R only uses the double equals ==, and that is for a precise reason.

The single equals functions the same as the assignment operator <-. So failure to use double equals can result in unexpected behavior:

x <- 1:10
x == 5  # logical vector 
x = 5   # overwrite vector x with value 5

Easy way to keep it straight.