0

I have recreated a simplified version of my problem using mtcars. I have two dataframes, df1 and df2:

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

eg.

head(df1)
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Merc 240D      24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230       22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2

dim(df1)
[1] 14 11

I want to create two new objects, nrows_df1 and nrows_df2, which both say the number of rows of the respective data frames, eg:

nrow_df1
[1] 14

I tried doing the following:

for (df in c(df1, df2)) {
    nam <- paste("nrows_", deparse(substitute(df)))
    assign(nam, nrow(df))
}

But it doesn't work. What is the correct code to create these variables, using the for loop?

1
  • "The only people who should use the assign function are those who fully understand why you should never use the assign function." - Greg Snow, R-help (July 2009) Commented Oct 19, 2020 at 9:09

1 Answer 1

2

Well, the correct way would be not to create such multiple dataframes having multiple corresponding variables in the global environment. Keep the dataframes in a list and you can do everything using this list itself using sapply/lapply :

df_list <- list(df1, df2)
n_rows <- sapply(df_list, nrow)
n_rows
#[1] 14 18

For the sake of completing the answer to get two separate variables in global environment, you can create a named list and use list2env.

list2env(setNames(as.list(n_rows), 
         paste0('nrow_df', seq_along(df_list))), .GlobalEnv)
nrow_df1
#[1] 14
nrow_df2
#[1] 18
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.