Re: [R] simple loop questions

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Sat, 23 Apr 2011 09:34:41 -0400

On Apr 23, 2011, at 6:31 AM, <xueke_at_pdx.edu> wrote:

> Hi all,
>
> I am trying to write a loop to return the matched index for a column
> of values. Here is an simple example of this,
>
> A B
> 0 5
> 1 2
> 2 2
> 3 4
> 4 1
> 5 4
> 6 2
>
> In this case, A is an index column for B. Now I have this new column
> C with just two values of 2 and 4. I want to match column C with
> column B, and return the matched indexes. So what I desire is to
> return:
>
> [1] 1 2 6
> [2] 3 5
>
> Since value 2 corresponds to indexes 1,2,6, and 4 corresponds to
> indexes 3,5.

Assuming this to be in a data.frame named dat:

 > dat$A[which(dat$B==2) ]
[1] 1 2 6
 > dat$A[which(dat$B==4) ]
[1] 3 5

Results of varying lengths generally need to be returned in list form:

 > sapply(c(2,4), function(x) dat$A[which(dat$B==x) ] ) [[1]]
[1] 1 2 6

[[2]]
[1] 3 5

>
> Is there any way to write a loop to have this done? Thank you for
> the help.
>
> Xueke
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



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. Received on Sat 23 Apr 2011 - 13:39:04 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 24 Apr 2011 - 16:40:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive