[R] if else loop

Sarah Goslee sarah.goslee at gmail.com
Tue Jul 5 17:13:37 CEST 2011


Hi Gary,

A solution in two pieces.

First, you need to be able to match the rows of your data frame. There
might be a more elegant way to do it, but I couldn't think of one that
gave the option of ordering or not, so I wrote a function:

isin <- function(dd, tomatch, ordered=TRUE) {
   # find tomatch in rows of df
   # order can be important or unimportant
   if(length(tomatch) != ncol(dd))
      stop("tomatch must have the same number of elements as df has columns.\n")
   if(ordered) {
      rowmatch <- apply(dd, 1, function(x){sum(x == tomatch) ==
length(tomatch)})
   } else {
      rowmatch <- apply(dd, 1, function(x)all(tomatch %in% x))
   }
   rowmatch
}

# test isin()

> set.seed(1234)
> dd <- data.frame(a = sample(1:20, 100, replace=TRUE), b = sample(5:24, 100, replace=TRUE))
> # isin() returns a row index so you can do something more than just return
> # something that looks just like the input, such as match the first two columns
> # but return entire rows
> dd[isin(dd, c(1, 19), ordered=FALSE),]
   a  b
73 1 19
98 1 19
> dd[isin(dd, c(10, 13), ordered=TRUE),]
[1] a b
<0 rows> (or 0-length row.names)
> dd[isin(dd, c(10, 13), ordered=FALSE),]
   a  b
3 13 10


On Tue, Jul 5, 2011 at 10:28 AM, gary engstrom <engstrom.gary at gmail.com> wrote:
> Dear R help
>
> I was hoping you might be able to show me how to write a loop function take
> would ccomplish this task.
>
> # code piece I am looking for
> if(subset(dd,c(1,23,ordered=F))is found))( print subset)
> else( continue evaluating subsets)
> subset(dd,isin(dd,c(1,23), ordered = FALSE))
> subset(dd,isin(dd,c(3,23),ordered=F))
> subset(dd,isin(dd,c(4,11),ordered=F))
> subset(dd,isin(dd,c(7,15),ordered=F))

Part II: I'm not entirely sure what you're trying to do. If c(1,23) is
not matched, do you want ALL of them, or should this be sequential?
And why not just check for all of them, rather than making it
conditional? Anyway, this should be enough to get you going:

if(nrow(dd[isin(dd, c(1, 23), ordered=FALSE),]) > 0) {
   dd[isin(dd, c(1, 23), ordered=FALSE),]
} else {
   dd[isin(dd, c(3, 23), ordered=FALSE), ]
}

# or, more elegantly:
> all.matches <- list(c(1, 23), c(3, 23), c(4, 11), c(7, 15))
> lapply(all.matches, function(x)dd[isin(dd, x, ordered=FALSE), ])
[[1]]
   a  b
24 1 23

[[2]]
[1] a b
<0 rows> (or 0-length row.names)

[[3]]
   a  b
89 4 11

[[4]]
[1] a b
<0 rows> (or 0-length row.names)


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list