You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对二维逻辑组织的Boolean变量生成百分比汇总矩阵?

Got it, let's tackle this problem step by step! You've got a 10×8 structure of boolean variables (likely grouped by rows and columns, with multiple observations per position) and want to calculate the percentage of TRUE values for each position, then output it as a clean matrix. Here's how to do this smoothly in R:

Step 1: Prepare Your Data

First, make sure your boolean data is structured correctly. If you have multiple repeated observations of the 10×8 matrix (e.g., 50 trials), a 3D array is the easiest format to work with. If you already have your data loaded, skip to Step 2—otherwise, here's a reproducible example to simulate your setup:

# Simulate 50 repeated 10x8 boolean matrices (replace with your actual data)
set.seed(123) # For consistent test results
n_trials <- 50
bool_array <- array(
  sample(c(TRUE, FALSE), 10*8*n_trials, replace = TRUE),
  dim = c(10, 8, n_trials) # Rows, Columns, Number of Observations
)

If your data is stored as a matrix where each cell is a boolean vector (e.g., 10 rows × 8 columns, each cell holds 20 TRUE/FALSE values), use this instead:

# Simulate a matrix of boolean vectors
bool_matrix_list <- matrix(
  lapply(1:80, function(x) sample(c(TRUE, FALSE), 20, replace = TRUE)),
  nrow = 10, ncol = 8
)
Step 2: Calculate Positive Value Percentages

Next, compute the percentage of TRUE values for each (row, column) position. We'll use apply for arrays or sapply for matrix lists:

For 3D Arrays:

# Calculate % of TRUEs for each cell
percent_matrix <- apply(bool_array, c(1, 2), function(cell_values) mean(cell_values) * 100)

For Matrix of Boolean Vectors:

# Calculate % of TRUEs for each cell vector
percent_matrix <- matrix(
  sapply(bool_matrix_list, function(vec) mean(vec) * 100),
  nrow = 10, ncol = 8
)
Step 3: Format & Print the Output Matrix

To make the output readable, format the percentages to 1 decimal place (adjust as needed) and add row/column labels:

# Format percentages as strings with % symbol
formatted_percent <- matrix(
  sprintf("%.1f%%", percent_matrix),
  nrow = 10, ncol = 8
)

# Add descriptive labels
rownames(formatted_percent) <- paste0("Row ", 1:10)
colnames(formatted_percent) <- paste0("Col ", 1:8)

# Print the clean matrix (no quotes)
print(formatted_percent, quote = FALSE)

Bonus: Pretty Table for R Markdown

If you're using R Markdown and want a publication-ready table, use the knitr package:

library(knitr)
kable(formatted_percent, caption = "Percentage of TRUE Values by Row and Column")

This will give you a clean, structured matrix that matches your 10×8 data layout, showing exactly how often each position had a positive (TRUE) value.


内容的提问来源于stack exchange,提问作者buhtz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:39:19