0

I have an empty data frame an I want to fill this data frame by adding new columns, but when I run the code it throws the following error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 0, 102

I know the problem is that my empty data frame does not have a row number. My question is, is there a way to fill an empty dataframe when you don't know how many rows your columns will have? In other words, when there is no row number in the empty data frame.

Currently I am trying:

df <- data.frame()
for (i in 1:(length(hojas)-1)) {
  dat <- read_excel(". . .", sheet = sheet_names[i])
  df <- cbind(df, dat)
}
Ricky
  • 1
  • 1
  • The error message indicates that one of your data frames (spreadsheets) has a different number of rows. There is almost certainly a better way to do this if you can be more specific about the spreadsheet you are reading and what you are trying to do. – dcarlson Nov 19 '21 at 23:39
  • `df <- if (!nrow(df)) dat else cbind(df, dat)` is one way to start. This does (as you suggest) *assume* that all sheets will have exactly the same number of rows. Ultimately, I suggest a better way is something like: `dats <- lapply(1:(length(hojas)-1), function(i) read_excel("...", sheet = sheet_names[i])) ; df <- do.call(cbind, dats)`, with no `for` loop required. – r2evans Nov 19 '21 at 23:40
  • Maybe this will help: https://stackoverflow.com/questions/9917545/r-define-dimensions-of-empty-data-frame – Dave2e Nov 20 '21 at 00:04
  • Thank you very much r2evans! Either solution worked just fine! – Ricky Nov 20 '21 at 00:25

0 Answers0