0

I have to write a one sample proportion Z test function in R. I need to have the sample proportion be the proportion of data in the first factor level. For example,

   data <- factor(c(NA, rep("a", 60), rep("b", 40)))
   table(data)
   a b
   60 40

And I need the sample proportion to be 60/100. Here is portion of my code and it is returning an error saying unexpected symbol in mtab <- addmargins(table(data)).

hyp_test <- function(data, hyp_val=NULL, alpha, alternative="two-sided",graph=FALSE) {

  n <- sum(!is.na(data))

  ifelse(is.factor(data),


     mtab <- addmargins(table(data))
     phat <- mtab[1]/mtab[3]
     qhat <- 1 - phat

     if(length(hyp_val) > 0) { 
       q <- 1-hyp_val
       SE.phat <- sqrt((hyp_val*q)/n) 
       ts.z <- (phat - hyp_val)/SE.phat
       p.val <- pnorm(ts.z)*2
       if(alternative=="less") {
         p.val <- pnorm(ts.z)
       }
       if(alternative=="greater") {
         p.val <- 1 - p.val
       }
     } 

Any help would be much appreciated. I need to basically find out how to find the sample proportion.

Mateusz1981
  • 1,817
  • 17
  • 33
Nick Garcia
  • 29
  • 1
  • 1
  • 7
  • table(data) displays a 1x2 table – Nick Garcia May 19 '16 at 05:40
  • 1
    Typically, [minimal](http://stackoverflow.com/help/mcve) and [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) code is very helpful and appreciated. In this case, though you are providing code, it is incomplete (your `ifelse` is hanging ...). Your error is because of this. Perhaps reading `?ifelse` would help you see a problem? – r2evans May 19 '16 at 05:53

1 Answers1

0

In addition to what r2evans states, you should review if statements and pnorm. This is a guesstimate of what you are trying to accomplish since the code is cut off.

hyp_test <- function(data, hyp_val=NULL, alpha, alternative="two-sided",graph=FALSE) {

  n <- sum(!is.na(data))
  mtab <- addmargins(table(data))
  phat <- mtab[1]/mtab[3]
  qhat <- 1 - phat
  q <- 1-hyp_val
  SE.phat <- sqrt((hyp_val*q)/n) 
  ts.z <- (phat - hyp_val)/SE.phat
  p.val <- ifelse(alternative=="two-sided", dnorm(ts.z)*2,ifelse(alternative=="less",1-dnorm(ts.z), dnorm(ts.z)))
  if(graph==TRUE) {plot(...)}
  return(p.val)
}
Jeonifer
  • 74
  • 2