Skip to content

How to write efficient R code

1 message · Tom Blackwell

#
Sebastian  -

For successive differences within a single column 'x'

differences <- c(NA, diff(x)),

same as

differences <- c(NA, x[-1] - x[-length(x)]).

See  help("diff"), help("Subscript").  The second version also
works when  x  is a matrix or a data frame, except now the result
is a matrix or data frame of the same size.

x <- data.frame(matrix(rnorm(1e+5), 1e+4))
dim(x)               # 10000    10
differences <- rbind(rep(NA, 10), x[-1, ] - x[-dim(x)[1], ])
dim(differences)     # 10000    10

However, you write "I need to do this for all the subsets of data
created by the numbers in one of the columns of the data frame ..."
and I'm not sure I understand how an 'id' column would create many
subsets of the data.  So the simple examples above may not answer
the question you are asking.

-  tom blackwell  -  u michigan medical school  -  ann arbor  -
On Tue, 17 Feb 2004, Sebastian Luque wrote: