[R] Putting x into the right subset
Uwe Ligges
ligges at statistik.uni-dortmund.de
Sat Jul 22 11:45:36 CEST 2006
John Wiedenhoeft wrote:
> Dear all,
>
> I'm sorry I have to bother you with this newbie stuff.
>
> Within a loop I obtain pairs of values x <- c(a, b). An empty set M is
> defined before the loop (as a list or whatever). Now I want to do the
> following: if there is a vector y in M that contains at least one of
> the values of x, then x shall be concatenated to y. If y doesn't contain
> any of the values in x, then x shall be put into M as a new vector. I
> first imagined it to be trivial but I'm having a hard time with the
> if-statement. I tried to define a function contains(value, vector),
> which returns FALSE or TRUE, but R complains that I tried to execute a
> "non-function"...
>
> Could anybody help a despaired newbie, please!
Example (maybe not efficient, but should do the trick):
M <- list()
temp <- NA
for(i in 1:20){
a <- sample(1:10, 1)
b <- sample(11:20, 1)
x <- c(a, b)
if(i > 1)
temp <- which(sapply(M, function(y) any(x %in% y)))[1]
if(!is.na(temp))
M[[temp]] <- c(M[[temp]], x)
else
M[[length(M) + 1]] <- x
}
> Thanks a lot,
> John
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
More information about the R-help
mailing list