Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending the row to data.table works differently than in data.frame: How and why?

Why does the following code not work?

library(data.table)
team_table <- as.data.table(matrix(NA,ncol = 11))
rbind(team_table,1:11)

While the same version with data.frame does?

team_table <-as.data.frame(matrix(NA,ncol = 11))
rbind(team_table,1:11)
like image 726
Djpengo Avatar asked Jan 21 '20 23:01

Djpengo


People also ask

Is data table better than data frame?

frame in R is similar to the data table which is used to create tabular data but data table provides a lot more features than the data frame so, generally, all prefer the data. table instead of the data.

How do I insert a row from one Dataframe to another?

append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value.

How do you append rows in R?

Using nrow() This syntax literally means that we calculate the number of rows in the DataFrame ( nrow(dataframe) ), add 1 to this number ( nrow(dataframe) + 1 ), and then append a new row new_row at that index of the DataFrame ( dataframe[nrow(dataframe) + 1,] ) — i.e., as a new last row.

How do I append multiple rows to a Dataframe in R?

The predefined function used to add multiple rows is rbind(). We have to pass a data frame and a vector having rows of data. So, let see the example code. If we want to extract multiple rows we can put row numbers in a vector and pass that vector as a row or column.


1 Answers

Convert to list and it should work

rbind(team_table,as.list(1:11))
#   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
#1: NA NA NA NA NA NA NA NA NA  NA  NA
#2:  1  2  3  4  5  6  7  8  9  10  11

It is also the same behavior with data.frame

rbind(team_table,as.list(1:11))
#  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
#1 NA NA NA NA NA NA NA NA NA  NA  NA
#2  1  2  3  4  5  6  7  8  9  10  11

Regarding why it fails, rbind in data.table is calling rbindlist and it is considering the vector (1:11) as a single column.

rbind(team_table,1:11)

Error in rbindlist(l, use.names, fill, idcol) : Item 2 has 1 columns, inconsistent with item 1 which has 11 columns. To fill missing columns use fill=TRUE.

If we convert it to a list with 11 element (data.frame or data.table are list with list elements i.e. columns having same length), it works because it would consider the number of columns to be the same

like image 171
akrun Avatar answered Nov 15 '22 00:11

akrun