如何查找向量中出现少于X次的所有值 [英] How to find all values which only appear less than X times in a vector

查看:126
本文介绍了如何查找向量中出现少于X次的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量,在这种情况下是一个字符向量.我希望所有元素仅在向量中出现一次,但是对于除1以外的其他限制,解决方案应该可以推广.

I have a vector, in this case a character vector. I want all the elements which only appear once in the vector, but the solution should be generalizable for limits other than 1.

如果使用table功能,则可以手动选择它们.我以为解决方案看起来像

I can pick them manually if I use the table function. I thought that the solution would look something like

frequencies <- table(myVector)
myVector[??@frequencies <= 1] 

但是首先,我不知道插槽名称必须输入??,并且在table对象上搜索文档使我无处可去.

But first of all, I don't know the slot name which will have to go into ??, and searches for documentation on the table object lead me to nowhere.

第二,而表的文档( )表示它返回类表"的对象",尝试使用某些随机词代替??来进行上述操作,但我没有收到无此类广告位"错误,但是

Second, while the documentation for table() says that it returns 'an object of class "table"', trying the above with some random word used instead of ??, I didn't get a "no such slot" error, but

错误:尝试从没有插槽的基本类(功能")的对象中获取插槽频率"

Error: trying to get slot "frequencies" from an object of a basic class ("function") with no slots

这似乎表明即使我知道插槽名称也无法使用上述功能.

which seems to indicate that the above won't function even if I knew the slot name.

那么正确的解决方案是什么?当我需要它们时,如何在table的单独列中找到它们?

So what is the correct solution, and how do I get at the separate columns in a table when I need them?

推荐答案

您不需要table:

vector <- c(1, 0, 2, 2, 3, 2, 1, 4)
threshold <- 1

Filter(function (elem) length(which(vector == elem)) <= threshold, vector)
# [1] 0 3 4

可以使用table,但是随后得到的结果是字符串而不是数字.您当然可以将它们转换回去,但是它却不那么优雅:

You can use table, but then you get the result as character strings rather than numbers. You can convert them back, of course, but it’s somehow less elegant:

tab <- table(vector)
names(tab)[tab <= threshold]
# [1] "0" "3" "4"

这篇关于如何查找向量中出现少于X次的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆