在下面的R
函数中,我想知道如何获取两个向量2
和a
的唯一元素(即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
答案 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)