Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add rows to empty data frames with header in R? [duplicate]

Tags:

dataframe

r

add

row

Possible Duplicate:
R: losing column names when adding rows to an empty data frame

I created an empty dataframe with column names only as follows

> compData <- data.frame(A= numeric(0), B= numeric(0)) > compData [1] A B <0 rows> (or 0-length row.names) > compData <- rbind(compData,c(5,443)) > compData   X5 X443 1  5  443 

in the above after adding one row the column names are changed. How can I add new row data to data-frame?

like image 511
Surjya Narayana Padhi Avatar asked Sep 27 '12 05:09

Surjya Narayana Padhi


People also ask

How do I initialize an empty data frame in R?

One simple approach to creating an empty DataFrame in the R programming language is by using data. frame() method without any params. This creates an R DataFrame without rows and columns (0 rows and 0 columns).

How do you add a value to an empty data frame?

Append Rows to Empty DataFrameDataFrame. append() function is used to add the rows of other DataFrame to the end of the given DataFrame and return a new DataFrame object.

How do you add a row to the top of a DataFrame in R?

The method insertRows() in R language can be used to append rows at the dataframe at any specified position. This method can also insert multiple rows into the dataframe. The new row is declared in the form of a vector. In the case of a blank row insertion, the new row is equivalent to NA.


1 Answers

Adding to a zero-row data.frame will act differently to adding to an data.frame that already contains rows

From ?rbind

The rbind data frame method first drops all zero-column and zero-row arguments. (If that leaves none, it returns the first argument with columns otherwise a zero-column zero-row data frame.) It then takes the classes of the columns from the first data frame, and matches columns by name (rather than by position). Factors have their levels expanded as necessary (in the order of the levels of the levelsets of the factors encountered) and the result is an ordered factor if and only if all the components were ordered factors. (The last point differs from S-PLUS.) Old-style categories (integer vectors with levels) are promoted to factors.

You have a number of options --

the most straightforward

 compData[1, ] <- c(5, 443) 

more complicated

Or you could coerce c(5,433) to a list or data.frame

rbind(compData,setNames(as.list(c(5,443)), names(compData))) 

or

rbind(compData,do.call(data.frame,setNames(as.list(c(5,443)), names(compData)))) 

But in this case you might as well do

do.call(data.frame,setNames(as.list(c(5,443)), names(compData))) 

data.table option

You could use the data.table function rbindlist which does less checking and thus preserves the names of the first data.frame

library(data.table) rbindlist(list(compData, as.list(c(5,443)) 
like image 117
mnel Avatar answered Sep 22 '22 16:09

mnel