0

To build off of this question: How to add rows to empty data frames with header in R?

If I happen to generate a data frame that is empty (I don't necessarily know which will be empty and which will contain data until I try to run the code) can I build in contigency: "if data frame is empty THEN assign zeros to all columns, if data frame has data, keep that data." ?

Thanks!

I can try to share some code if it's helpful, but if we can work with the code in the related example that will help me immensely.

Community
  • 1
  • 1
rstunt
  • 35
  • 1
  • 5
  • I like the looks if it, but I'm getting this error: Error in as.Date.numeric(value) : 'origin' must be supplied In addition: There were 50 or more warnings (use warnings() to see the first 50) Warning messages: 1: In `[<-.factor`(`*tmp*`, iseq, value = 0) : invalid factor level, NA generated – rstunt May 20 '15 at 19:17
  • someone suggested this: if(nrow(data)==0) data[1,] <- 0; else data – rstunt May 20 '15 at 19:21
  • My function was based on the dataset showed in the other link. If your dataset have factor columns, it may give warnings as showed. YOu may need to update the post with an example and expected output based on that – akrun May 20 '15 at 19:21
  • I suggested that and posted the comment as a solution – akrun May 20 '15 at 19:22
  • http://stackoverflow.com/questions/27750484/attempting-to-replace-character-value-in-dataframe-with-numeric-value-error this seems to be relevant, but I'm not sure how to use it just yet. – rstunt May 20 '15 at 19:34

1 Answers1

0

Try

 f1 <- function(dat){
  if(nrow(dat)==0){
    dat[1,] <- 0
         }
   else dat
   dat}

using the data from the link,

 f1(compData)
 #  A B
 #1 0 0
akrun
  • 874,273
  • 37
  • 540
  • 662