On Mon, 2 Aug 2010, Roy Davy wrote:
Hi,
I am having some problems setting up some indicators and would appreciate any
help.
I have some data called 'lights' with 3 variables called x, a and b.
x - is the date
a - equals 1 to indicate an 'on' button is activated
b - equals 1 to indicate an 'off' button is activated
Essentially i wannt to create 2 new variables c and d
c - will reflect the current state of the light (1 being on)
d - will be a count for how many days the light has been on
here's some data with the date omitted to illustrate what i have and what is
required.
a b c d
0 0 0 0
0 0 0 0
1 0 1 1
1 0 1 2
0 0 1 3
0 0 1 4
1 0 1 5
0 0 1 6
0 0 1 7
0 1 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1 0 1 1
0 0 1 2
0 0 1 3
0 0 1 4
0 1 0 0
0 0 0 0
After some considerable time i have managed to create variable c with a
loop but it's really slow with the volume of data i have. Could anyone
please show me how to do this efficiently?
Two solutions:
1) inline - if you are configured to compile source,
use the inline package to render your loop as C or Fortran
2) findInterval - like this:
on.pos <- which(a==1)
off.pos <- which(b==1)
last.on <- c(0,on.pos)[ 1 + findInterval(1:20,on.pos)]
last.off <- c(0,off.pos)[ 1 + findInterval(1:20,off.pos)]
cee <- as.integer(last.on>last.off)
Don't use 'c' as a variable name as it is a common function
HTH,
Chuck
I hope this is clear...
Thanks
Roy
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cbe...@tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.