Skip to content

Instantly share code, notes, and snippets.

@dewittpe
Created September 9, 2014 18:38
Show Gist options
  • Save dewittpe/054f54d7fe9443d739a0 to your computer and use it in GitHub Desktop.
Save dewittpe/054f54d7fe9443d739a0 to your computer and use it in GitHub Desktop.
# Tweet from Erin Jonaitis:
# Hey nerds. y[x==1] is shorthand for "elements of y where the corresponding x
# is 1." What if I want y[i] such that x[i+e]==1?
set.seed(42)
# random data for example
y <- round(rnorm(30), 2)
x <- sample(1:3, size = 30, replace = TRUE)
# view the two vectors together
dat <- rbind(y, x)
dat
# simple index of y
y[x == 1]
# find the index of the x vector which equals 1
idx <- which(x == 1)
dat[, idx]
# solve for i, assuming that e is a vector of lenght 1
# idx = i + e
# i = idx - e
e <- 3
i <- idx - e
dat[, i]
rbind(dat[, i],
dat["x", i + e])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment