R table() Function - Frequency Statistics

R 语言实例R Language Examples

R table() function is used to count the frequency of each value in a vector and generate a frequency table.

table() can also compute cross-frequencies (contingency tables) of multiple categorical variables, and is a basic tool for data analysis.

The syntax of the table() function is as follows:

table(x, y = NULL)

Parameter description:

  • xCategorical variable or vector.

  • yOptional, second categorical variable, used to generate a cross-tabulation.

Example

# Count frequencies of each category
colors <- c("red", "blue", "red", "green", "blue", "red", "blue", "green", "red", "red")
freq <- table(colors)
print("Color frequencies:")
print(freq)

# Proportions
prop <- prop.table(freq)
print("Color proportions:")
print(prop)

Executing the above code produces the following output:

[1] "颜色频数:"
colors
红 蓝 绿
 5  3  2
[1] "颜色比例:"
colors
  红   蓝   绿
0.5  0.3  0.2

table() can also generate multi-dimensional cross-tabulations:

Example

# Cross-tabulation: Gender × Purchased
gender <- c("male", "female", "male", "female", "male", "male", "female", "female")
purchase <- c("yes", "yes", "no", "yes", "yes", "no", "no", "yes")

cross_table <- table(gender, purchase)
print("Gender × Purchased cross-tabulation:")
print(cross_table)

# Row percentages
print("Row percentages:")
print(prop.table(cross_table, margin = 1))

Executing the above code produces the following output:

[1] "性别 × 购买 交叉表:"
      purchase
gender 否 是
    男  2  2
    女  1  3
[1] "行百分比:"
      purchase
gender   否   是
    男 0.50 0.50
    女 0.25 0.75

R 语言实例R Language Examples

Other extensions