I have a contingency table of counts, and I want to extend it with corresponding proportions of each group.

Some sample data (`tips`

data set from `ggplot2`

package):

```
library(ggplot2)
head(tips, 3)
# total_bill tip sex smoker day time size
# 1 17 1.0 Female No Sun Dinner 2
# 2 10 1.7 Male No Sun Dinner 3
# 3 21 3.5 Male No Sun Dinner 3
```

First, use `table`

to count smoker vs non-smoker, and `nrow`

to count total number of subjects:

```
table(tips$smoker)
# No Yes
# 151 93
nrow(tips)
# [1] 244
```

Then, I want to calculate percentage of smokers vs. non smokers. Something like this (ugly code):

```
# percentage of smokers
options(digits = 2)
transform(as.data.frame(table(tips$smoker)), percentage_column = Freq / nrow(tips) * 100)
# Var1 Freq percentage_column
# 1 No 151 62
# 2 Yes 93 38
```

Is there a better way to do this?

(even better it would be to do this on a set of columns (which I enumerate) and have output somewhat nicely formatted) (e.g., smoker, day, and time)

If it's conciseness you're after, you might like:

```
prop.table(table(tips$smoker))
```

and then scale by 100 and round if you like. Or more like your exact output:

```
tbl <- table(tips$smoker)
cbind(tbl,prop.table(tbl))
```

If you wanted to do this for multiple columns, there are lots of different directions you could go depending on what your tastes tell you is clean looking output, but here's one option:

```
tblFun <- function(x){
tbl <- table(x)
res <- cbind(tbl,round(prop.table(tbl)*100,2))
colnames(res) <- c('Count','Percentage')
res
}
do.call(rbind,lapply(tips[3:6],tblFun))
Count Percentage
Female 87 35.66
Male 157 64.34
No 151 61.89
Yes 93 38.11
Fri 19 7.79
Sat 87 35.66
Sun 76 31.15
Thur 62 25.41
Dinner 176 72.13
Lunch 68 27.87
```

If you don't like stack the different tables on top of each other, you can ditch the `do.call`

and leave them in a list.

- How to get AIC from Conwayâ€“Maxwell-Poisson regression via COM-poisson package in R?
- R : how to simply repeat a command?
- session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium
- How to show code but hide output in RMarkdown?
- remove kernel on jupyter notebook
- Function to calculate R2 (R-squared) in R
- Center Plot title in ggplot2
- R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph
- R multiple conditions in if statement
- What does "The following object is masked from 'package:xxx'" mean?
- Saving a high resolution image in R
- Change bar plot colour in geom_bar with ggplot2 in r
- Converting data frame column from character to numeric
- Extract Month and Year From Date in R
- How to combine two lists in R
- Extract year from date
- Ifelse statement in R with multiple conditions
- R dplyr: Drop multiple columns
- Remove legend ggplot 2.2
- Remove all of x axis labels in ggplot
- how to remove multiple columns in r dataframe?
- Aggregate multiple columns at once
- Changing fonts in ggplot2
- How to specify "does not contain" in dplyr filter
- how to use the Box-Cox power transformation in R
- Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe
- Having trouble setting working directory
- Coerce multiple columns to factors at once
- How to declare a vector of zeros in R
- Create empty data frame with column names by assigning a string vector?
- Explain ggplot2 warning: "Removed k rows containing missing values"
- R for loop skip to next iteration ifelse
- Error: package or namespace load failed for ggplot2 and for data.table
- How do I change the default library path for R packages
- Select first and last row from grouped data
- R * not meaningful for factors ERROR
- Error: could not find function "%>%"
- Raise to power in R
- In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric
- Error - replacement has [x] rows, data has [y]
- Merge r brings error "'by' must specify uniquely valid columns"
- Non-numeric Argument to Binary Operator Error in R
- Convert row names into first column
- Append data frames together in a for loop
- Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis
- R Markdown - changing font size and font type in html output
- Replace all occurrences of a string in a data frame
- How to convert dataframe into time series?
- Sum across multiple columns with dplyr
- Removing NA observations with dplyr::filter()
- [Move to Extend contigency table with proportions (percentages)]

- Trying to merge 2 dataframes but get ValueError
- How to show all of columns name on pandas dataframe?
- Python Pandas - Find difference between two data frames
- Pandas get the most frequent values of a column
- Display all dataframe columns in a Jupyter Python Notebook
- How to convert column with string type to int form in pyspark data frame?
- Display/Print one column from a DataFrame of Series in Pandas
- Binning column with python pandas
- Selection with .loc in python
- Set value to an entire column of a pandas dataframe
- Pandas create empty DataFrame with only column names
- Python: pandas merge multiple dataframes
- Spark dataframe: collect () vs select ()
- 'DataFrame' object has no attribute 'sort'
- Remove Unnamed columns in pandas dataframe
- Convert float64 column to int64 in Pandas
- Python Pandas iterate over rows and access column names
- Display rows with one or more NaN values in pandas dataframe
- ValueError: Length of values does not match length of index | Pandas DataFrame.unique()
- Convert List to Pandas Dataframe Column
- Pandas Split Dataframe into two Dataframes at a specific row
- Pandas dataframe groupby plot
- Removing space from dataframe columns in pandas
- Get total of Pandas column
- Python - How to convert JSON File to Dataframe
- Strip / trim all strings of a dataframe
- Merge two dataframes by index
- pandas how to check dtype for all columns in a dataframe?
- Joining Spark dataframes on the key
- Provide schema while reading csv file as a dataframe
- Pandas group-by and sum
- PySpark 2.0 The size or shape of a DataFrame
- How to concatenate multiple column values into a single column in Panda dataframe
- Convert Pandas DataFrame to JSON format
- pandas dataframe convert column type to string or categorical
- How to add multiple columns to pandas dataframe in one assignment?
- Fetching distinct values on a column using Spark DataFrame
- How to Add Incremental Numbers to a New Column Using Pandas
- Pandas KeyError: value not in index
- How to split data into 3 sets (train, validation and test)?
- Split / Explode a column of dictionaries into separate columns with pandas
- Group dataframe and get sum AND count?
- Save Dataframe to csv directly to s3 Python
- Pandas dataframe fillna() only some columns in place
- how to sort pandas dataframe from one column
- PySpark: multiple conditions in when clause
- What is dtype('O'), in pandas?
- Filter Pyspark dataframe column with None value
- Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
- How to create a DataFrame from a text file in Spark
- [Move to Extend contigency table with proportions (percentages)]

- Count the Number of Tables in a SQL Server Database
- SQL count rows in a table
- How to count the occurrence of certain item in an ndarray?
- Laravel Eloquent - distinct() and count() not working properly together
- How to count items in JSON data
- Powershell: count members of a AD group
- How to count how many values per level in a given factor?
- Count number of rows by group using dplyr
- C++ - how to find the length of an integer
- JPA COUNT with composite primary key query not working
- Count distinct value pairs in multiple columns in SQL
- Fastest way to determine if record exists
- SQL Query with Join, Count and Where
- pandas python how to count the number of records or rows in a dataframe
- Javascript counting number of objects in object
- Sum values in foreach loop php
- How to obtain the total numbers of rows from a CSV file in Python?
- Pandas count(distinct) equivalent
- In Firebase, is there a way to get the number of children of a node without loading all the node data?
- Get number of digits with JavaScript
- Multiple aggregate functions in HAVING clause
- count distinct values in spreadsheet
- Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES
- How do I count occurrence of duplicate items in array
- Count number of occurrences for each unique value
- How can I divide one column of a data frame through another?
- SUM of grouped COUNT in SQL Query
- Count how many files in directory PHP
- How to get multiple counts with one SQL query?
- Count multiple columns with group by in one query
- GROUP BY and COUNT in PostgreSQL
- PHP - count specific array values
- SQL to Entity Framework Count Group-By
- postgresql COUNT(DISTINCT ...) very slow
- Count with IF condition in MySQL query
- Extend contigency table with proportions (percentages)
- Count indexes using "for" in Python
- How to count number of records per day?
- COUNT / GROUP BY with active record?
- How to count the number of true elements in a NumPy bool array
- How to count the number of occurrences of a character in an Oracle varchar value?
- Java count occurrence of each item in an array
- How to count check-boxes using jQuery?
- Fast way to discover the row count of a table in PostgreSQL
- Trying to get the average of a count resultset
- Count number of rows per group and add result to original data frame
- jQuery count number of divs with a certain class?
- SQL query for finding records where count > 1
- SQL: How to get the count of each distinct value in a column?
- Calculate average in java
- [Move to Extend contigency table with proportions (percentages)]