【问题标题】:length of the unique elements of listed vectors in RR中列出向量的唯一元素的长度
【发布时间】:2019-01-18 18:02:11
【问题描述】:

在下面的R 函数中,我想知道如何获得两个向量ab 的唯一元素(即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

【问题讨论】:

  • 长度应该是长度?
  • 我想你可以检查一下length()lengths() 之间的区别。它们都存在,但具有不同的能力。
  • lengths 的结果是正确的
  • 我已经在下面发布了解决方案,你的结果应该是 60 for a 和 40 for b 显示里面的元素!
  • @DataScience,但这只是针对其中一个向量而不是两者。我希望它返回 2 2

标签: r function


【解决方案1】:

使用lapply()sapply(),因为您的对象是一个列表。我想你可能会检查length()lengths() 之间的区别。它们都存在,但具有不同的能力。我提供两种解决方案foo1foo2

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

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多