R中列出的向量的唯一元素的长度

时间:2019-01-18 18:02:11

标签: r function

在下面的R函数中,我想知道如何获取两个向量2a的唯一元素(即b)的长度?

这是我尝试没有成功的事情:

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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

这是答案

您正在使用取消列表功能-因此您又回到了向量长度的开头!

改为使用此代码

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)