Skip to content

Instantly share code, notes, and snippets.

@arunsrinivasan
Created March 18, 2014 20:32
Show Gist options
  • Select an option

  • Save arunsrinivasan/9628914 to your computer and use it in GitHub Desktop.

Select an option

Save arunsrinivasan/9628914 to your computer and use it in GitHub Desktop.
Clarifying twitter question regarding usage of `.I`
require(data.table)
DT <- as.data.table(mtcars)
# directly using .SD
set.seed(45L)
system.time(ans1 <- DT[, .SD[sample(.N, 5L)], by=gear])
# user system elapsed
# 0.009 0.000 0.010
# using `.I`
set.seed(45L)
system.time(ans2 <- DT[DT[, .I[sample(.N, 5L)], by=gear]$V1])
# user system elapsed
# 0.003 0.000 0.004
setcolorder(ans2, names(ans1)) # gear goes first in (1)
identical(ans1, ans2)
# [1] TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment