的R - 选择元素,如果有比向量n更多(或更少) [英] R - select elements if there more (or less) than n in vector
问题描述
我需要改变在向量元素的值。但我想改变只对其中有小于n个实例的元素。
我用这个metodh,用数据$ GENE是要改变的载体。
数据$ GENE [其中(单位:%名称(表(数据$基因)[表(数据$ GENE)LT数据$ GENE%; 10]))<< - 其他
这是一个有点令人费解,有没有更多的succint的方式?
更新:在回答下面的评论:其实是一个很简单的情况下
> VEC< - C(代表('富',5),代表('foo1',2),代表('foo2的',1),代表('foo3',3),众议员('酒吧',6) )
>表(VEC)
VEC
巴富foo1 foo2的foo3
6 5 2 1 3
> VEC [其中(在%名VEC%(表(VEC)[表(VEC)小于5]))]下; - '其他'
>表(VEC)
VEC
巴富等
6 5 6
我只想做第2步所以它不太令人费解就像你说的,你只需要计算表一次。此外,你不需要这
如您在您的方式使用它。
Y'LT; - 表(VEC)
VEC [以%名VEC%(γ[Y小于5])]&下; - 其他
I need to change the value of elements in a vector. But I want to change only the elements for which there are less then n instances.
I used this metodh, with Data$GENE being the vector to be changed.
Data$GENE[which(Data$GENE %in% names(table(Data$GENE)[table(Data$GENE) < 10]))] <<- 'other'
It's a bit convoluted, is there a more succint way?
UPDATE: answering to the comments below: actually is a quite easy case!
> vec <- c(rep('foo', 5), rep('foo1', 2), rep('foo2', 1), rep('foo3', 3), rep('bar', 6))
> table(vec)
vec
bar foo foo1 foo2 foo3
6 5 2 1 3
> vec[which(vec %in% names(table(vec)[table(vec) < 5]))] <- 'other'
> table(vec)
vec
bar foo other
6 5 6
I would just do it in 2 steps so it's less convoluted as you say and you only need to compute the table once. Also, you don't need which
as you use it in your approach.
y <- table(vec)
vec[vec %in% names(y[y < 5])] <- "other"
这篇关于的R - 选择元素,如果有比向量n更多(或更少)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!