1

I have data before/after that i want to analyse using McNemar test.

before <-c(0,0,0,0,0,0)
after<-c(1,0,0,1,0,0)
table(before,after)

  after
before 0 1
     0 4 2

As you probably already guesses problem with that table is that I'm missing theoretically possible "1" level in "before".

Is there a good clean way of creating that additional row with all zeros ?

  • 1
    Please read the manual (`?table`), and you will find several references to factor _levels_, e.g. `d <- factor(rep(c("A","B","C"), 10), levels = c("A","B","C","D","E"))` et c. – Henrik Jan 12 '16 at 07:45

2 Answers2

2

We can use factor with levels specified

 table(factor(before, levels=0:1),after)
 #    after
 #   0 1
 # 0 4 2
 # 1 0 0
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @MaciejKarczewski So simple that it has already been asked and answered in SO. –  Jan 12 '16 at 07:25
2

Try before <- factor(rep(0,6),levels = c(0,1))

Also you can change levels of an existing factor the following way:

x <- factor(1:5)
levels(x) <- c(levels(x),"ABC")
Alexandre Halm
  • 979
  • 1
  • 8
  • 18