문제

A friend wrote up this function for determining unique members of a vector. I can't figure out (mentally) what this one line is doing and it's the crux of the function. Any help is greatly appreciated

myUniq <- function(x){
  len = length(x)                    # getting the length of the argument
  logical = rep(T, len)              # creating a vector of logicals as long as the arg, populating with true
  for(i in 1:len){                   # for i -> length of the argument
    logical = logical & x != x[i]   # logical vector =  logical vector & arg vector where arg vector != x[i] ??????
    logical[i] = T
  }
x[logical]
}

This line I can't figure out:

logical = logical & x != x[i]

can anyone explain it to me?

Thanks, Tom

도움이 되었습니까?

해결책

logical is a vector, I presume a logical one containing len values TRUE. x is a vector of some other data of the same length.

The second part x != x[i] is creating a logical vector with TRUE where elements of x aren't the same as the current value of x for this iteration, and FALSE otherwise.

As a result, both sides of & are now logical vector. & is an element-wise AND comparison the result of this is TRUE if elements of logical and x != x[i] are both TRUE and FALSE otherwise. Hence, after the first iteration, logical gets changed to a logical vector with TRUE for all elements x not the same as the i=1th element of x, and FALSE if they are the same.

Here is a bit of an example:

logical <- rep(TRUE, 10)
set.seed(1)
x <- sample(letters[1:4], 10, replace = TRUE)

> x
 [1] "b" "b" "c" "d" "a" "d" "d" "c" "c" "a"
> logical
 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
> x != x[1]
 [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
> logical & x != x[1]
 [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

This seems very complex. Do you get the same results as:

unique(x)

gives you? If I run my x above through myUniq() and unique() I get the same output:

> myUniq(x)
[1] "b" "d" "c" "a"
> unique(x)
[1] "b" "c" "d" "a"

(well, except for the ordering...)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top