[R] matching element of a vector to i-2nd element

Hervé Pagès hpages at fredhutch.org
Sun Jul 23 21:19:28 CEST 2017


On 07/23/2017 11:43 AM, Davide Piffer wrote:
> I have a df with a vector v. For each element of the vector, I want to
> know whether the i-2nd element is the same as the ith element. For
> example:
> given
> v=c(A,C,D,C) the result should be:
> I attempted something using indexing in a for loop such as (bad,
> incorrect example):
>   for (i in v){
>    if [i]==[i-2] print T
> else print F
> }
> However, this is obviously wrong.

Why don't you provide code that is actually valid R code so we
can run it. Then we can see if it does the right thing or not.

> Can someone provide a nice way to solve this?

Does this do what you want?

   isSameAsPrevious <- function(v, k=1) c(rep(FALSE, k), head(v,n=-k) == 
tail(v, n=-k))


 > isSameAsPrevious(v, 2)


> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://urldefense.proofpoint.com/v2/url?u=https-3A__stat.ethz.ch_mailman_listinfo_r-2Dhelp&d=DwICAg&c=eRAMFD45gAfqt84VtBcfhQ&r=BK7q3XeAvimeWdGbWY_wJYbW0WYiZvSXAJJKaaPhzWA&m=YfPp2NbGMLV4frEpzG4QQFssqMnld91RlQHDdWcvFtw&s=-KVWCgOZsuCGKiZ7aXq4jhZBw97MrEzg19X8yFD60l8&e=
> PLEASE do read the posting guide https://urldefense.proofpoint.com/v2/url?u=http-3A__www.R-2Dproject.org_posting-2Dguide.html&d=DwICAg&c=eRAMFD45gAfqt84VtBcfhQ&r=BK7q3XeAvimeWdGbWY_wJYbW0WYiZvSXAJJKaaPhzWA&m=YfPp2NbGMLV4frEpzG4QQFssqMnld91RlQHDdWcvFtw&s=HGLgncA6cBilW_DkIzjBEizqo1AmvlshmOHQr4td1vc&e=
> and provide commented, minimal, self-contained, reproducible code.

Hervé Pagès

Program in Computational Biology
Division of Public Health Sciences
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N, M1-B514
P.O. Box 19024
Seattle, WA 98109-1024

E-mail: hpages at fredhutch.org
Phone:  (206) 667-5791
Fax:    (206) 667-1319

More information about the R-help mailing list