Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add percentages to a contingency table

Tags:

r

I have a question about the table() function in R. I want to add an extra column to show percentages from counts made by table(). I have a data frame like this:

delta=data.frame(x1=c("x001","x001","x002","x002","x001","x001","x002"),x2=c(1,2,1,1,1,1,1))

When I compute table() for this data frame I got this:

table(delta$x1,delta$x2)

       1 2
  x001 3 1
  x002 3 0

It is possible to add percentages in this table or there is any function or package in R to compute something like this:

       1 2  Number Percentage
  x001 3 1    4     0.5714286
  x002 3 0    3     0.4285714

Thanks for your help.

like image 445
Duck Avatar asked Apr 07 '13 18:04

Duck


Video Answer


1 Answers

You can use prop.table and addmargins

tbl <- table(delta$x1,delta$x2)

prop.table(tbl)

# 1         2
# x001 0.4285714 0.1428571 
# x002 0.4285714 0.0000000

addmargins(tbl)

# 1 2 Sum
# x001 3 1   4
# x002 3 0   3
# Sum  6 1   7

EDIT

Of course you can do something like

rowSums(prop.table(tbl)) 
     x001      x002 
0.5714286 0.4285714 

But my answer is to say that there are some built-in function in R that complete the table function.

like image 96
agstudy Avatar answered Nov 15 '22 05:11

agstudy