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)
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With