Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select the column of a matrix based on increasing numbers

I have a matrix with 4 columns (below example)

   a  b c   d
1 10 85 0 115
2 15 74 0 125
3 18 65 0 130
4 20 64 0 150

I want to select just a column whose number increases along the length of the column (A & D column).

   A   D
1 10 115
2 15 125
3 18 130
4 20 150
df<-data.frame(A=c(10,15,18,20),B=c(85,74,65,64),
               C=c(0,0,0,0),D=c(115,125,130,150))

Note

My actual data is huge and this example is a test to explain better.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is an inbuilt function is.unsorted for this purpose which checks if a vector is sorted without the cost of actually sorting it. So this should work faster on large datasets.

strictly_increasing <- function(x) !is.unsorted(x, strictly = TRUE)

df[sapply(df, strictly_increasing)]

#   A   D
#1 10 115
#2 15 125
#3 18 130
#4 20 150

You may also use it with dplyr

library(dplyr)

df %>% select(where(strictly_increasing))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading