Skip to content

Instantly share code, notes, and snippets.

@jennybc
Last active August 29, 2015 14:06
Show Gist options
  • Save jennybc/f6fe97e137b5a7df2b9e to your computer and use it in GitHub Desktop.
Save jennybc/f6fe97e137b5a7df2b9e to your computer and use it in GitHub Desktop.
How quickly indexing with numeric can burn you

Inspired by recent @johnmyleswhite tweets on indexing (though they focus more on NA stuff)

My standard advice to R novices is "don't worry about numeric vs integer too much, for now", but I just created an indexing example that scares me.

I did not realize it was sooo easy to create this gotcha when indexing with numeric (which I know is not a great idea).

x <- 4:1 + 0.1
str(x <- x - 0.1)
##  num [1:4] 4 3 2 1
(1:4)[4:1]
## [1] 4 3 2 1
(1:4)[x]
## [1] 3 3 2 1

title: "2014-09-18_numeric-index-gotcha.r" author: "jenny" date: "Thu Sep 18 07:46:47 2014"

#' ---
#' output:
#' html_document:
#' keep_md: TRUE
#' ---
#' Inspired by recent @johnmyleswhite tweets on indexing (though they focus more
#' on NA stuff)
#'
#' My standard advice to R novices is "don't worry about numeric vs integer too
#' much, for now", but I just created an indexing example that scares me.
#'
#' I did not realize it was sooo easy to create this gotcha when indexing with
#' numeric (which I know is not a great idea).
x <- 4:1 + 0.1
str(x <- x - 0.1)
(1:4)[4:1]
(1:4)[x]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment