R语言:如何通过for循环与assign创建数据框行数变量
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:
- When you use
c(df1, df2), R converts the data frames into a single atomic vector (sincec()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. deparse(substitute(df))inside the loop only returns the loop variable namedf, not the original namesdf1ordf2. So you'd end up creating a single variablenrows_dfinstead 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

