3

While working with data.frame it is simple to insert new value by using row number;

df1 <- data.frame(c(1:3))    
df1[4,1] <- 1

> df1
  c.1.3.
1      1
2      2
3      3
4      1

It is not working with data.table;

df1 <- data.table(c(1:3))
df1[4,1] <- 1
Error in `[<-.data.table`(`*tmp*`, 4, 1, value = 1) : i[1] is 4 which is out of range [1,nrow=3].

How can I do it?

Borax
  • 83
  • 1
  • 5

1 Answers1

3

Data Tables were designed to work much faster with some common operations like subset, join, group, sort etc. and as a result have some differences with data.frames. Some operations like the one you pointed out will not work on data.tables. You need to use data.table - specific operations.

dt1 <- data.table(c(1:3))
rbindlist(list(dt1, list(1)), use.names=FALSE)
dt1

#    V1
# 1:  1
# 2:  2
# 3:  3
# 4:  1
Katia
  • 3,784
  • 1
  • 14
  • 27
  • 1
    Maybe relevant: https://stackoverflow.com/questions/16652533/insert-a-row-in-a-data-table and https://stackoverflow.com/questions/16792001/add-a-row-by-reference-at-the-end-of-a-data-table-object – Frank May 06 '18 at 23:39