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

如何在R中不加载RDS文件获取其行列数?

How to Get RDS File Row/Column Counts Without Loading the Entire File in R

Great question! You absolutely can retrieve the row and column counts of an RDS file without loading the entire dataset into memory—this is a total lifesaver for large files where loading everything would hog your RAM or crash your session. Below are a few reliable methods, depending on your needs:

Method 1: Base R (Quick Column Count, Limited Row Count Support)

If you know your RDS file stores a data frame/tibble, you can grab the column count by reading just the structure (0 rows) of the dataset. This avoids loading any actual data:

# Get column count
col_count <- ncol(readRDS("your_file.rds", nrows = 0))

Note: Base R doesn't have a built-in way to get the row count without loading at least part of the data. For row counts, you'll want to use one of the package-based methods below.

The arrow package provides efficient, memory-safe tools to work with RDS files (and many other data formats). It can read metadata directly without loading the full dataset:

  1. First install the package if you haven't:
install.packages("arrow")
  1. Use these commands to get your dimensions:
library(arrow)

# Read the RDS as an Arrow dataset (no full data loaded)
rds_data <- read_rds("your_file.rds", as_data_frame = FALSE)

# Extract row and column counts
row_count <- nrow(rds_data)
col_count <- ncol(rds_data)

# Print results
cat("Total rows:", row_count, "\nTotal columns:", col_count)

This works seamlessly with data frames, tibbles, and other tabular structures, and it's optimized for large files.

Method 3: rds Package (Lightweight RDS-Specific Tool)

If you want a minimal, RDS-focused solution, the rds package lets you read the file's header metadata directly:

  1. Install the package:
install.packages("rds")
  1. Extract dimensions from the header:
library(rds)

# Read the RDS file header
rds_header <- rds_read_header("your_file.rds")

# Check if the object is a data frame, then get dimensions
if (rds_header$object_type == "data.frame") {
  dimensions <- rds_header$attributes$dim
  row_count <- dimensions[1]
  col_count <- dimensions[2]
  cat("Rows:", row_count, "\nColumns:", col_count)
}

This is perfect if you only need metadata and want to avoid heavier packages.

Important Note

All these methods assume your RDS file contains a tabular object (like a data frame or tibble). If your RDS stores non-tabular data (e.g., a list, machine learning model, or custom object), the "row/column count" concept doesn't apply—you'll need to first check the object type via the header metadata before proceeding.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:58:57