length of the unique elements of listed vectors in R

50 views Asked by At

In my R function below, I was wondering how I could get the length of the unique elements (which is 2) of two vectors a and b?

Here is what I tried without success:

foo <- function(...){
    L <- list(...)
    lengths(unique(unlist(L)))
}

a = rep(c("a", "b"), 30) # Vector `a`
b = rep(c("a", "b"), 20) # Vector `b`

foo(a, b)  # the function returns 1 1 instead of 2 2
2

There are 2 answers

0
Darren Tsai On BEST ANSWER

Use lapply() or sapply() because your object is a list. I think you might check the difference between length() and lengths(). They both exist but have different abilities. I provide two solutions foo1 and foo2:

foo1 <- function(...){
  L <- list(...)
  sapply(L, function(x) length(unique(x)))
}

foo2 <- function(...){
  L <- list(...)
  lengths(lapply(L, unique))
}

a = rep(c("a", "b"), 30) # Vector `a`
b = rep(c("a", "b"), 20) # Vector `b`

foo1(a, b)
# [1] 2 2

foo2(a, b)
# [1] 2 2
0
AudioBubble On

Here is the answer

You were using the unlist function - so you were back at the start with the vector lengths!

use this code instead

foo <- function(a,b){

  L <- list(a,b)
  lengths(unique(L)) ### this return 1 1

}

a = rep(c("a", "b"), 30) # Vector `a`

b = rep(c("a", "b"), 20) # Vector `b`

foo(a, b)