3

I want to know how to generate an automatized sequence from 0 to 100, with numbers each 5 positions only, all the rest should be NA values. At the end I would like to have something like this:

> labCol
[1]  0 NA NA NA NA  5 NA NA NA NA 10 NA NA NA NA 15 NA  .....  100

I have done this example manually like this, but it is time consuming:

labCol <- c(0, NA, NA, NA, NA, 5, NA, NA, NA, NA, 10, NA, NA, NA, NA, 15, NA, ... 100 )

I can't find an option in the seq() function to do this.

This problem is because I'm doing a Heat Map with the function heatmap.2() of the gplots package, and the column labels are too close to read. Neither can I set the labels every 5 or 10 positions. That is why I need generate my own label sequence with NA values to avoid this overlapping.

Any suggestion is welcome :)

Darwin PC
  • 871
  • 3
  • 23
  • 34

2 Answers2

6

Try this:

labCol <- seq(0, 100, 1)
labCol[labCol %% 5 != 0] <- NA

This generates a sequence from 0 to 100 by 1, then just sets all sequence values not divisible by 5 to NA.

Alex A.
  • 5,466
  • 4
  • 26
  • 56
  • thanks @Alex A. it works!! pardon my ignorance, but what means `%%` and `!=0` ? – Darwin PC Mar 20 '15 at 04:54
  • 1
    @DarwinPC: As BondedDust mentioned, `%%` gets the [modulus](http://en.wikipedia.org/wiki/Modulo_operation), i.e. the remainder after integer division. For any number not divisible by 5, the remainder will be nonzero, so we can set those cases to `NA`. `!=0` means not equal to 0. – Alex A. Mar 20 '15 at 14:07
1

You could also create a NA vector and then fill the elements

 labCol <- rep(NA,100)
 labCol[seq(1,101, 5)] <- seq(0,100,5)
 labCol
 #[1]   0  NA  NA  NA  NA   5  NA  NA  NA  NA  10  NA  NA  NA  NA  15  NA  NA
 #[19]  NA  NA  20  NA  NA  NA  NA  25  NA  NA  NA  NA  30  NA  NA  NA  NA  35
 #[37]  NA  NA  NA  NA  40  NA  NA  NA  NA  45  NA  NA  NA  NA  50  NA  NA  NA
 #[55]  NA  55  NA  NA  NA  NA  60  NA  NA  NA  NA  65  NA  NA  NA  NA  70  NA
 #[73]  NA  NA  NA  75  NA  NA  NA  NA  80  NA  NA  NA  NA  85  NA  NA  NA  NA
 #[91]  90  NA  NA  NA  NA  95  NA  NA  NA  NA 100
akrun
  • 874,273
  • 37
  • 540
  • 662