R: How to add a row that has different number of columns than the rest of the data frame?

combine two data frames in r with different columns
r data frame manipulation
r add column to dataframe with value
r add calculated column to dataframe
r dataframe index column
r add column to dataframe based on other columns
create dataframe in r with column names
create data frame r

I have a dataframe that looks like this:

set <- data.frame("id"=c("one", "two","three"), "line_number"=c("1", "2", "3"), 
              "content_type"=c("paragraph", "paragraph","paragraph"), 
              "text"=c("this is a sample","first batch is:", "second batch is:"), 
              "section"=c("introduction","content","summary"))

So it looks like:

  set(view)
  id       line_number      content_type     text                   section
  one           1            paragraph       this is a sample     introduction
  two           2            paragraph       first batch is:        content
  three         3            paragraph       second batch is:       summary

I want to add one row on top of this data frame, which only has content in one column, now it looks like:

  set(view)
  id       line_number      content_type     text                   section
                                             Sample Report
  one           1            paragraph       this is a sample     introduction
  two           2            paragraph       first batch is:        content
  three         3            paragraph       second batch is:       summary

And R can just automatically fill in NA wherever it's needed.

I try to use rbind but it won't let me do it because numbers of columns do not match. Is there other way to do it? Maybe a loop?

Thank you! I really appreciate it.

This should do it

set <- data.frame("id"=c("one", "two","three"), "line_number"=c("1", "2", "3"), 
                  "content_type"=c("paragraph", "paragraph","paragraph"), 
                  "text"=c("this is a sample","first batch is:", "second batch is:"), 
                  "section"=c("introduction","content","summary"), stringsAsFactors = FALSE)
x <- data.frame(text = "Sample Report", stringsAsFactors = FALSE)
dplyr::bind_rows(set,x )

15 Easy Solutions To Your Data Frame Problems In R, Discover how to create a data frame in R, change column and row names, access Data frames are particularly handy to store multiple data vectors, which makes it Check if you have put an equal number of arguments in all c() functions that Otherwise, the other variables will be interpreted as “NA”. In R, manipulating data using data frame may require many operations such as: adding a column, editing column data, removing a column, etc. In this article, we will show you how to add a column to a data frame. Let’s say that we have a data frame as the following and we will use it to practice how to add a column to a data frame in R.

base R

set2[setdiff(names(set),names(set2))] <- NA
rbind(set2,set)
#               text    id line_number content_type      section
# 1    Sample Report  <NA>        <NA>         <NA>         <NA>
# 2 this is a sample   one           1    paragraph introduction
# 3  first batch is:   two           2    paragraph      content
# 4 second batch is: three           3    paragraph      summary

or for a one liner that doesn't change set2:

rbind('[<-'(set2,setdiff(names(set),names(set2)),value= NA),set)

dplyr

dplyr::bind_rows(set2,set)
#               text    id line_number content_type      section
# 1    Sample Report  <NA>        <NA>         <NA>         <NA>
# 2 this is a sample   one           1    paragraph introduction
# 3  first batch is:   two           2    paragraph      content
# 4 second batch is: three           3    paragraph      summary

data.table

data.table::rbindlist(list(set2,set),fill=TRUE)
#                text    id line_number content_type      section
# 1:    Sample Report    NA          NA           NA           NA
# 2: this is a sample   one           1    paragraph introduction
# 3:  first batch is:   two           2    paragraph      content
# 4: second batch is: three           3    paragraph      summary

note on column order

The column order is given by the first data.frame, that's why column text was moved to the left. Add [names(set)] to any answer to get the original order back.

data

set <- data.frame("id"=c("one", "two","three"), "line_number"=c("1", "2", "3"), 
                  "content_type"=c("paragraph", "paragraph","paragraph"), 
                  "text"=c("this is a sample","first batch is:", "second batch is:"), 
                  "section"=c("introduction","content","summary"))

set2 <- data.frame(text ="Sample Report")   

R Data Frame Operations, We had created a Data Frame of the world population in R, as shown We can add single or multiple observations/rows to a Data Frame in R using rbind() function. Create a new Data Frame of the same number of variables/columns. On the other hand, while adding rows the number of elements in the  Commands to extract rows and columns. Command to extract a column as a data frame. Command to extract an element. Suppose you have a data frame, df, which is represented as follows. Below we've created a data frame consisting of three vectors that include information such as height, weight, and age.

Other alternatives to what has already been given:

set <- data.frame("id"=c("one", "two","three"), "line_number"=c("1", "2", "3"), 
              "content_type"=c("paragraph", "paragraph","paragraph"), 
              "text"=c("this is a sample","first batch is:", "second batch is:"), 
              "section"=c("introduction","content","summary"), stringsAsFactors = FALSE)
x <- data.frame(text = "Sample Report", stringsAsFactors = FALSE)
using dplyr
library(dplyr)
d1 <- full_join(set,x)
d1 <- d1 %>% arrange(!is.na(line_number),line_number)

The second step will help ensure you get your "Sample Report" in the first row.

using base R
d2 <- merge(set,x,all = T)
d2 <- d2[order(d2$line_number,na.last=F),]

Again, the second line of code above will help ensure you get your "Sample Report" in the first row. In both cases, the merging variable is not explicitly stated (but R by default takes the variables that is common to both datasets i.e. the "text" variable).

4 data wrangling tasks in R for advanced beginners, I've created a sample data set with three years of revenue and profit data from Apple, (R adds its own row numbers if you don't include row names.) data frame to see its structure, you'll see that the year is being treated as a number and in R is adding a new column to a data frame based on one or more other columns. You may want to combine data from different sources in your analysis. Generally speaking, you can use R to combine different sets of data in three ways: By adding columns: If the two sets of data have an equal set of rows, and the order of the rows is identical, then adding columns makes sense.

Working with data in a data frame, diabetes <- read.csv("r-intro-files/diabetes.csv") class(diabetes) A data frame can also be created from vectors, with the data.frame function. As with a matrix, a data frame can be accessed by row and column with [,] . This is because the row may contain data of different types, and a vector can only hold elements of all​  How To Add Rows And Columns To A Data Frame Much in the same way that you used the [,] and $ notations to access and change single values, you can also easily add columns to writers_df : Appending rows to an existing data frame is somewhat more complicated.

4 Transform Tables, How to solve common data science tasks with R's Tidyverse. Because tables are made of multiple data structures that work together: You want to sort the rows of a data frame in ascending order by the values in one or more as the other columns in the data frame, because mutate() will add the vector as a new column. You also have the option of using rbind to add multiple rows at once – or even combine two R data frames. If you want to add rows this way, the two data frames need to have the same number of columns.

15 Easy Solutions To Your Data Frame Problems In R, These issues have been selected from the most recent and sticky or upvoted Stack Overflow posts. As you can see, there are different data structures that impose In other words, you can also set the header for your data frame. To check how many rows and columns you have in your data frame, you  The data frame result now has an extra observation compared to baskets.df. rb ind() can take multiple arguments, as long as they’re compatible. In this case, you bind a vector c(7, 4) at the bottom of the data frame. Note that R, by default, sets the row number as the row name for the added rows.

Comments
  • Try dplyr::bind_rows()
  • this is a smart hack in base R and very compact, but you need to be sure you have zero intersection between datasets, and it's probably much slower than rbind. With dplyr I don't see any added value compared to bind_rows