0

I am new to R and need help. Please help me out in...

How to create a data frame (say myData2) in R that is similar to an existing data frame (say myData1 with 5 columns), but it is blank. That is, the new data frame has 5 columns as are in myData1 but it has no data in the rows.

I want the output to have "0 obs. of 5 variables".

talat
  • 68,970
  • 21
  • 126
  • 157
Monsta
  • 59
  • 3
  • 7
  • 4
    You can use `newData <- oldData[0,]` but the question is really, why would you want to do that? It's normally better not to create data row-wise in R. Instead, do it column-wise. – talat Jun 29 '16 at 11:59
  • 1
    Possible duplicate of [Create an empty data frame with index from another data frame](http://stackoverflow.com/questions/18176933/create-an-empty-data-frame-with-index-from-another-data-frame) – ArunK Jun 29 '16 at 12:00
  • Thanks @docendodiscimus :) newData <- oldData[0,] WORKS... Actually I wanted to use RBIND later to that... RBIND was not allowing me to append rows as the "newData" data frame was not having equal number of columns (bCoz it was having zero columns). – Monsta Jun 29 '16 at 12:07
  • then probably, rather than creating an empty df, you need to use `merge` instead of `rbind` – Cath Jun 29 '16 at 12:09
  • @Arun maybe the same question but different langages, this question is for `R` and the one you're suggesting is `Python`... – Cath Jun 29 '16 at 12:10
  • @Cath, My bad. I must have clicked the wrong link. I'm pretty sure I've seen one similar for R too.. Here's the link to one. http://stackoverflow.com/questions/9917545/r-define-dimensions-of-empty-data-frame. I'm unsure, how to change the flag status. – ArunK Jun 29 '16 at 12:17

1 Answers1

0

Here, assuming the column names and their `data types. However, you can change it according to you requirements

  myData2<- data.frame(x= character(0), y= numeric(0), a = character(0), b= integer(0), c = numeric(0))

  myData2
  # [1] x y a b c
  # <0 rows> (or 0-length row.names)

  str(myData2)
  # 'data.frame':   0 obs. of  5 variables:
  #  $ x: Factor w/ 0 levels: 
  #  $ y: num 
  #  $ a: Factor w/ 0 levels: 
  #  $ b: int 
  #  $ c: num 

  dim(myData2)
  # [1] 0 5

  class(myData2)
  # [1] "data.frame"
Sowmya S. Manian
  • 3,723
  • 3
  • 18
  • 30