CER
CER

Reputation: 889

Subsetting a datatable with 1:n

While mucking around with some data I encounter a problem with sub setting a data.table

Sample of my datatable

library(data.table)

datatab <- structure(list(a = c(183591969L, 183591969L, 183591984L, 183591727L, 
                     183591733L), b = c(183591984L, 183591985L, 183591985L, 183591729L, 
                                        183591737L)), .Names = c("a", "b"), class = c("data.table", "data.frame"
                                        ), row.names = c(NA, -5L)) 

I simply try to split the whole thing with a variable like

a <- 2
datatab[1:a,]

but get the error

Warning message: In 1:a : numerical expression has 5 elements: only the first used

while

df <- as.data.frame(datatab)
df[1:a,]

and

datatab[1:2,]

work as expected.

Might be something obvious I didn't get. I guess it has something to do with the way the data.table library handles the data but I would appreciate if someone can clarify. As my real data is much larger I would like to avoid the as.data.frame()

Upvotes: 1

Views: 55

Answers (1)

akuiper
akuiper

Reputation: 215117

You are using a as a parameter which happens to be a column of the data.table, use a different name for the parameter:

x <- 2
datatab[1:x,]

#           a         b
#1: 183591969 183591984
#2: 183591969 183591985

Upvotes: 4

Related Questions