[R] Comparison of vectors in a matrix
Tony Plate
tplate at acm.org
Tue Nov 10 19:06:24 CET 2009
Nice problem!
If I understand you correctly, here's how to do it (with list-based matrices):
> set.seed(1)
> (x <- matrix(lapply(rpois(10,2)+1, function(k) sample(letters[1:10], size=k)), ncol=2, dimnames=list(1:5,c("A","B"))))
A B
1 Character,2 Character,5
2 Character,2 Character,5
3 Character,3 Character,3
4 Character,5 Character,3
5 Character,2 "i"
> x[1,1]
[[1]]
[1] "c" "b"
> x[1,2]
[[1]]
[1] "c" "d" "a" "j" "f"
> (y <- cbind(x, "A-B"=apply(x, 1, function(ab) setdiff(ab[[1]], ab[[2]]))))
A B A-B
1 Character,2 Character,5 "b"
2 Character,2 Character,5 "g"
3 Character,3 Character,3 Character,3
4 Character,5 Character,3 Character,2
5 Character,2 "i" Character,2
> y[1,3]
[[1]]
[1] "b"
>
-- Tony Plate
esterhazy wrote:
> Hi,
>
> I have a matrix with two columns, and the elements of the matrix are
> vectors.
>
> So for example, in line 3 of column 1 I have a vector v31=("marc", "robert,
> "marie").
>
> What I need to do is to compare all vectors in column 1 and 2, so as to get,
> for example setdiff(v31,v32) into a new column.
>
> Is there a way to do this in R?
>
> Thanks!
More information about the R-help
mailing list