Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a add a row to a data frame in R?

Tags:

dataframe

r

In R, how do you add a new row to a data frame once the data frame has already been initialized?

So far I have this:

df <- data.frame("hi", "bye") names(df) <- c("hello", "goodbye")  #I am trying to add "hola" and "ciao" as a new row de <- data.frame("hola", "ciao")  merge(df, de) # Adds to the same row as new columns  # Unfortunately, I couldn't find an rbind() solution that wouldn't give me an error 

Any help would be appreciated

like image 427
Rilcon42 Avatar asked Feb 12 '15 00:02

Rilcon42


People also ask

How do I add rows to a DataFrame?

You can create a DataFrame and append a new row to this DataFrame from dict, first create a Python Dictionary and use append() function, this method is required to pass ignore_index=True in order to append dict as a row to DataFrame, not using this will get you an error.

How do I add row numbers to a DataFrame in R?

To Generate Row number to the dataframe in R we will be using seq.int() function. Seq.int() function along with nrow() is used to generate row number to the dataframe in R. We can also use row_number() function to generate row index.

How do you add a row to a structure in R?

To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function. The basic syntax of rbind() is as shown below. Now we shall learn to add the observations/rows using rbind() below.

Which function is used to add row in a DataFrame in R studio?

In this article, we will see how to add rows to a DataFrame in R Programing Language. To do this we will use rbind() function. This function in R Language is used to combine specified Vector, Matrix or Data Frame by rows.


2 Answers

Let's make it simple:

df[nrow(df) + 1,] = c("v1","v2") 
like image 163
Matheus Araujo Avatar answered Sep 26 '22 17:09

Matheus Araujo


Like @Khashaa and @Richard Scriven point out in comments, you have to set consistent column names for all the data frames you want to append.

Hence, you need to explicitly declare the columns names for the second data frame, de, then use rbind(). You only set column names for the first data frame, df:

df<-data.frame("hi","bye") names(df)<-c("hello","goodbye")  de<-data.frame("hola","ciao") names(de)<-c("hello","goodbye")  newdf <- rbind(df, de) 
like image 40
Parfait Avatar answered Sep 25 '22 17:09

Parfait