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.

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 Commented May 20, 2015 at 19:17
  • someone suggested this: if(nrow(data)==0) data[1,] <- 0; else data Commented May 20, 2015 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 Commented May 20, 2015 at 19:21
  • I suggested that and posted the comment as a solution Commented May 20, 2015 at 19:22
  • stackoverflow.com/questions/27750484/… this seems to be relevant, but I'm not sure how to use it just yet. Commented May 20, 2015 at 19:34

1 Answer 1

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
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.