R中列出的向量的唯一元素的长度
在下面的R中列出的向量的唯一元素的长度,r,function,R,Function,在下面的R函数中,我想知道如何获得两个向量a和b的唯一元素(即2)的长度 以下是我尝试但未成功的结果: 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 in
R
函数中,我想知道如何获得两个向量a
和b
的唯一元素(即2
)的长度
以下是我尝试但未成功的结果:
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
下面是答案
您使用的是unlist函数-因此您回到了向量长度的起点
请改用此代码
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)
foo使用lappy()
或sapply()
,因为您的对象是一个列表。我想你可以检查一下length()
和length()
之间的区别。他们都存在,但有不同的能力。我提供了两种解决方案foo1
和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
foo1长度应该是长度?我想你可以检查length()
和length()
之间的差异。它们都存在,但有不同的能力。长度的结果是正确的。我已经在下面发布了解决方案。a的结果应该是60,b的结果应该是40,以显示里面的元素@数据科学,但这只是一个向量,而不是两个向量。我要它退2