简体   繁体   中英

Plotting points from only certain rows in a matrix in R

I am new to R so it's probably very basic, but I am trying to add colored points for certain values to a plot of a matrix "m". I need to add points from the same matrix, but only for the rows containing values within the range 169 to 179. What code can I use for this? I tried:

p <- which(m[,2]==169:179
## and
points (p, col="blue")

and it doesn't work. How can I write these codes properly to put these coordinates in blue on the graph? thanks!

You can try to define a function that test if a number is in between your two values:

inbetween = function(x)
{
     return ( x >= 169 & x <= 179 )
}

And then call it on each value of m[,2] with the function sapply: ind = sapply( m[,2], inbetween ) Which gives you a vector of True or False according if the given value if in the range or not. Then taking p = m[ind,] will give you the rows of m at those selected indices.

It would be good if you could share an example of your data. In general it makes more sense to plot data from a data frame, opposed to a matrix. We can use the pre-installed mtcars dataset to demonstrate your solution.

Let's first have a look at the data available in the dataset:

summary(mtcars)

Next, we can filter the data that we want to display. In this case we are filtering mtcars$mpg (the column with the name mpg ) for values between 15 and 20. To make it easier, we assign this filtered data frame as a new data frame.

mtcars_filtered <- mtcars[mtcars$mpg >= 15 & mtcars$mpg <= 20 , ]

Lastly, we can plot the data. In this case, we want the mpg column to be the x values and hp to be the y values. type is used to specify how we want to display it ( "p" for points), and col is used to specify the color ( "blue" for blue).

plot(mtcars_filtered$mpg, mtcars_filtered$hp, type = 'p', col = 'blue')

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM