R Func Table
# R table() Function - Frequency Statistics
[ R Language Examples](#)
The R table() function is used to count the frequency of each value in a vector, generating a frequency table.
table() can also count the cross-frequency of multiple categorical variables (contingency table), making it a fundamental tool for data analysis.
The syntax of the table() function is as follows:
table(x, y = NULL)
**Parameter Description:**
* **x** A categorical variable or vector.
* **y** Optional, a second categorical variable used to generate a cross-tabulation.
## Example
# Count frequency of each category
colors<-c("Red", "Blue", "Red", "Green", "Blue", "Red", "Blue", "Green", "Red", "Red")
freq <-table(colors)
print("Color Frequency:")
print(freq)
# Proportion
prop <-prop.table(freq)
print("Color Proportion:")
print(prop)
Executing the above code produces:
"Color Frequency:" colors Red Blue Green 5 3 2 "Color Proportion:" colors Red Blue Green 0.5 0.3 0.2
table() can also generate multi-dimensional cross-tabulations:
## Example
# Cross-tabulation: Gender Γ Purchase
gender <-c("Male", "Female", "Male", "Female", "Male", "Male", "Female", "Female")
purchase <-c("is", "is", "No", "is", "is", "No", "No", "is")
cross_table <-table(gender, purchase)
print("Gender Γ Purchase Crosstab:")
print(cross_table)
# Row Percentage
print("Row Percentage:")
print(prop.table(cross_table, margin =1))
Executing the above code produces:
"Gender Γ Purchase Crosstab:" purchase gender No is Male 2 2 Female 1 3 "Row Percentage:" purchase gender No is Male 0.50 0.50 Female 0.25 0.75
[ R Language Examples](#)
YouTip