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

R语言:如何通过for循环与assign创建数据框行数变量

Fixing the For Loop to Count Rows for Your Data Frames

Hey there! Let's break down why your original loop isn't working, then fix it up properly.

The Problem with Your Original Code

Your loop has two key issues:

  1. When you use c(df1, df2), R converts the data frames into a single atomic vector (since c() coerces elements to a common type). This means your loop isn't iterating over the full data frames—you're actually looping through individual column values instead.
  2. deparse(substitute(df)) inside the loop only returns the loop variable name df, not the original names df1 or df2. So you'd end up creating a single variable nrows_df instead of the two you want.

The Correct For Loop Implementation

Instead of looping over the data frame objects directly, loop over their names as strings. Then use get() to retrieve the actual data frame, and assign() to create your row-count variables:

First, let's confirm your initial data setup (just to be thorough):

library(dplyr)
df1 <- mtcars %>% filter(mpg > 20)
df2 <- mtcars %>% filter(mpg < 20)

Now the working loop:

# Iterate over the names of your data frames
for (df_name in c("df1", "df2")) {
  # Fetch the data frame using its name
  current_df <- get(df_name)
  # Create the new variable name (e.g., "nrows_df1")
  result_name <- paste0("nrows_", df_name)
  # Assign the row count to the new variable
  assign(result_name, nrow(current_df))
}

After running this, you'll have nrows_df1 and nrows_df2 in your environment, each holding the correct row count for their respective data frames.

A Bonus "R-Friendly" Alternative

While you asked specifically for a for loop, it's worth mentioning that managing related objects in a list is generally cleaner in R (avoids cluttering your global environment with lots of individual variables):

# Store your data frames in a named list
df_list <- list(df1 = df1, df2 = df2)
# Calculate row counts for all items in the list
nrows_list <- lapply(df_list, nrow)

# If you still want these values as separate global variables:
list2env(nrows_list, envir = .GlobalEnv)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 17:02:56