Alysha - 11 months ago 52

R Question

Is there a quick way to code for those specific vectors? Like I only want to use every 4th column in my matrix then plot the selected columns. I'm very new to R and have absolutely no idea what I'm doing. I know how to select a single vector and how to select a certain number in a row but that doesn't really help.

Answer Source

If you're looking to extract every 4th column from a matrix you can use `seq()`

.
Here's an example. I made a dummy dataset: `foo<-matrix(c(rep(c(4,3,2,7),100)),nrow=10,ncol=10)`

Then you can store the column indexes that you want from your matrix like so:

`colsyouwant<-seq(from = 4, to = ncol(foo), by = 4)`

from = whatever column you'd like to start from, in your case the 4th. Then you specify where you'd like to stop, so I used the `ncol`

function to count how many columns are in the matrix. In this case my matrix isn't a multiple of 4 but it doesn't matter because `seq`

stops before then. Then by=4 because you want to select every fourth column.

The `colsyouwant`

now equals to `4 8`

. Simply use brackets and the name of your variable to get the columns you want out. `foo[,colsyouwant]`

. Here the brackets just specify what part of the matrix I want as an output, it goes [rows,columns]. Since I want all the rows I leave that spot blank and then specify the rows using the `colsyouwant`

variable, or in other words `4 8`

.