# [R] print vectors with consecutive numbers

James Wei zwei0428 at hotmail.com
Fri Aug 22 16:16:58 CEST 2014

```Hi Jorge,

Thanks so much, it is working perfectly. There are so many for me to learn.

Cheers.

James

From: jorgeivanvelez at gmail.com
Date: Fri, 22 Aug 2014 22:28:40 +1000
Subject: Re: [R] print vectors with consecutive numbers
To: zwei0428 at hotmail.com
CC: r-help at r-project.org

Hi James,

Try
mat[, apply(mat, 2, function(x) any(diff(x) == 1))]

HTH,

Jorge.-

On Fri, Aug 22, 2014 at 10:18 PM, James Wei <zwei0428 at hotmail.com> wrote:

Hi all,

I have a matrix with consecutive and non-consecutive numbers

in columns. For example, the first 2 columns have consecutive numbers. I want R

to print only columns with consecutive numbers. Here is the matrix and how I

did using conditional statement:

##

mat=matrix(data=c(9,2,3,4,5,6,10,13,15,17,19,22,

25,27,29,31,34,37,39,41),ncol=5)

mat

difference = diff(mat)==1

difference

y1=difference[1,]

y2=difference[2,]

y3=difference[3,]

y=(y1|y2|y3)

y

if (y=="TRUE") mat else 0

##

However, R still print all 5 columns, not the first 2

columns I wanted. I got the Warning message:

In if (y == "TRUE") mat else 0 :

the condition has

length > 1 and only the first element will be used

How can I change the code to get only the first 2 columns

with consecutive numbers printed? I am new to R.

[[alternative HTML version deleted]]

______________________________________________

R-help at r-project.org mailing list

https://stat.ethz.ch/mailman/listinfo/r-help