[R] print vectors with consecutive numbers

Jorge I Velez jorgeivanvelez at gmail.com
Fri Aug 22 14:28:40 CEST 2014


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.
>
> Thanks in advance for your help. James
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list