Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中列出的向量的唯一元素的长度_R_Function - Fatal编程技术网

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