source('utils.R') # Section 3; Question 1 (EPage 668): # source('chap_14_sect_3_question_1_data.R') d = DF$Winter - DF$Summer ad = abs(d) r = rank( ad, ties.method='average' ) z = rep( 0, length(d) ) z[ d > 0 ] = 1 w = sum( z * r ) n = length(d) max_d_value = n*(n+1)/2 max_d_value - w p_value = sum( c( 1, 1, 2, 2, 3, 4, 5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1) )/2^n print( sprintf( 'w= %d; p_value= %.6f', w, p_value ) ) # Section 3; Question 2: # n = 5 pw = c( 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 1 )/2^n # P_W(W=w) print( cumsum( rev(pw) ) ) # Section 3; Question 3 (EPage 676): # source('chap_14_sect_3_question_3_data.R') d = DF$High - DF$Moderate ad = abs(d) r = rank( ad, ties.method='average' ) z = rep( 0, length(d) ) z[ d > 0 ] = 1 w = sum( z * r ) n = length(d) m = n*(n+1)/4 # expected mean under H_0 v = n*(n+1)*(2*n+1)/24 # expected variance under H_0 z = ( w - m ) / sqrt(v) p_value = 2*(1-pnorm(abs(z))) print( sprintf( 'w= %d; p_value= %.6f', w, p_value ) ) # Section 3; Question 4 (EPage 676): # source('chap_14_sect_3_question_4_data.R') res = signed_rank(DF$Score[-8]) # drop the eigth sample p_value = 2*(1-pnorm(abs(res$z))) print( sprintf( 'w= %d; p_value= %.6f', res$w, p_value ) ) # 3.5: # source('../Chapter5/chap_5_sect_3_question_2_data.R') res = signed_rank(DF$Ratio - 0.8) p_value = pnorm(res$z) print( sprintf( 'w= %d; p_value= %.6f', res$w, p_value ) ) # 3.6: # source('../Chapter13/case_study_13_3_1_data.R') res = signed_rank(DF$After - DF$Before) p_value = 2*(1-pnorm(abs(res$z))) print( sprintf( 'w= %d; p_value= %.6f', res$w, p_value ) ) # 3.8: # source('../Chapter8/chap_8_sect_2_question_6_data.R') res = signed_rank(DF$Mothered - DF$Unmothered) p_value = 2*(1-pnorm(abs(res$z))) print( sprintf( 'w= %d; p_value= %.6f', res$w, p_value ) ) t.test( DF$Mothered, DF$Unmothered ) # gives the same conclusion as the signed rank test above # 3.9: # source('../Chapter9/chap_9_sect_2_question_6_data.R') x = DF[ DF$Alcohol==1, ]$Age y = DF[ DF$Alcohol==0, ]$Age res = rank_sum( x, y ) p_value = pnorm(res$z) # a one sided test expect mean(x) < mean(y) print( sprintf( 'w_prime= %.2f; p_value= %.6f', res$w_prime, p_value ) ) t.test( x, y, alternative='less' ) # 3.10 # source('../Chapter9/table_9_3_1.R') x = DF$Non_Confined y = DF$Confined res = rank_sum( x, y ) p_value = 2*(1-pnorm(abs(res$z))) print( sprintf( 'w_prime= %.2f; p_value= %.6f', res$w_prime, p_value ) ) t.test( x, y )