1

I've got a vector test <- c(1:90) (approximately representing 3 months in daily time-steps), I want to give a value to a variable during a run of a model only when the time is between days 10 and 20 in each month:

//model code

if(month-day>10 && month-day<20)
{
    parameter <- 10
} else {
    parameter <- 5
}

By finding the modulus (test%%30), I can get an vector containing the days for each month, but need to get the positions of the days 10-20 for each month out of this subsequent vector

> test%%30
[1] 1 2 3 4 [...] 27 28 29 0 1 2 3 ...

I've just hit a brickwall with how to get the values I want (i.e. in this simple example I want test[11:19], test[41:49] and test[71:79], but there must be a way to get these values using some clever mathematical operators that I can't think of at the moment...

ChrisW
  • 4,970
  • 7
  • 55
  • 92

3 Answers3

1

To convert to blocks of 1:30, use:

(test-1)%%30+1

If you wanted to get numbers 10:19, (a block of 10 beginning at 10) you could have used:

test[(((test-1)%%30+1)%/%10)==1]

But as you want a block of 9 beginning at 11 you need to think about the shift after the modulus a little more:

test[(((test-1)%%30-1)%/%9)==1]
 [1] 11 12 13 14 15 16 17 18 19 41 42 43 44 45 46 47 48 49 71 72 73 74 75 76 77
[26] 78 79
James
  • 65,548
  • 14
  • 155
  • 193
0
x <- 1:90
param <- rep(5, length(x))
param[x%%30 > 10 & x%%30 < 20] <- 10
#Double check output 
cbind(x, param)
Chase
  • 67,710
  • 18
  • 144
  • 161
0

To expand a little on joran's answer, here's what I would do:

test <- c(1:90)
days <- test%%30
positions <- test[days %in% 10:20]

This returns a vector with the position in test of each day falling between 10 and 20.

Not totally sure why you need the position, though; couldn't your code just use:

for(x in 1:90) {
    if(days[x]>=10 && days[x]<=20) {
        parameter <-  10
    } else {
        parameter <- 5
    }
}

Or am I missing something here?

EDITED TO ADD: Whoops, I should have noted that in such a case, parameter might be better used as a vector - I just didn't make the code up that way.

TARehman
  • 6,659
  • 3
  • 33
  • 60
  • I want the middle 10 days of *each* month. Hmm.. perhaps that didn't come across in my question – ChrisW Apr 17 '12 at 14:51
  • Are you using different numbers of day for each month, e.g. February is 28, March is 31, etc? – TARehman Apr 17 '12 at 14:53
  • No - it's a more simplistic representation than that – ChrisW Apr 17 '12 at 14:54
  • 1
    So, if test is the number of days overall of the study (or whatever), then days is simply that vector broken up into 30 unit blocks. So, selecting the values between 10 and 20 in that should be the middle 10 days of each month. – TARehman Apr 17 '12 at 14:56