【问题标题】:Find the unique values of a named vector with their corresponding names查找具有相应名称的命名向量的唯一值
【发布时间】:2018-04-05 04:48:35
【问题描述】:

正如标题所示,我想找出一个命名向量的唯一值及其对应的名称

library(dplyr)
temp <-   runif(10000, 0, 10) %>% ceiling() %>% as.integer()
names(temp) <-  c('a', 'b', "c", 'd', 'e','f', 'g', "s", "s", 'r') %>% rep(100)

命名向量的前 10 个值如下所示。

temp[1:10]
a b c d e f g s s r 
7 4 9 2 5 7 9 8 8 8 

我可以找到唯一值或唯一名称。但我不知道如何找到它们,也不知道如何匹配它们。

temp %>% unique()
names(temp) %>% unique()

【问题讨论】:

  • 你的意思是temp[unique(names(temp))]
  • 前 10 个值的预期值是多少?
  • @Sotos 是的,实际上这就是我想要的。有点简单,但它从我的想法中消失了。谢谢。你可以把它写下来作为答案,我会接受,这样我们就可以完成帖子了
  • 不确定我们要做什么,如果我们匹配唯一名称,结果将为您提供第一个匹配项,请尝试:x &lt;- c(1,2,3); names(x) &lt;- c("a", "a", "b"); x[unique(names(x))] 这将提供1,3

标签: r vector dplyr


【解决方案1】:

对于命名向量,您可以简单地做,

temp[unique(names(temp))]

#or

temp[!duplicated(names(temp))]

#or

temp[match(unique(names(temp)), names(temp))]

【讨论】:

    【解决方案2】:

    我认为您最好在数据框中将名称和值分开列。然后您可以使用distinct 来获取唯一的组合。

    library(dplyr)
    temp <-   c(7, 4, 9, 2, 5, 7, 9, 8, 8, 8)
    names(temp) <-  c('a', 'b', "c", 'd', 'e','f', 'g', "s", "s", 'r') 
    
    data.frame(temp = temp[1:10],
               temp_name = names(temp[1:10])) %>% 
      distinct()
    

    【讨论】:

    • 现在我们需要将其转换回命名向量吗?
    • 鉴于向量的名称不是唯一的,在向量上使用名称属性似乎很奇怪。命名向量很少比数据框中的两列更有用。我唯一能想到我真的需要一个命名向量是在shiny 中定义选择列表时。
    • 如果你想要它,只需添加%&gt;% {setNames(.$temp,.$temp_name)}
    猜你喜欢
    • 2021-12-06
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多