简体   繁体   English

从r中的列表替换向量中的特定数字

[英]replace specific number in a vector from a list in r

I've been working on this problem and can't seem to figure out the proper solution. 我一直在解决这个问题,似乎无法找出正确的解决方案。 Ultimately I'm going to use dplyr in order to group by and apply a function to a column. 最终,我将使用dplyr进行分组并将功能应用于列。 I turned the column into a vector. 我把专栏变成了向量。 Here is a snippet: 这是一个片段:

vec1 <- append(append(append(rep(1,3),rep(2,6)), rep(3,5)),rep(4,2))

if the number repeats more than 3 times, I want to change the following number to 1. So in the vector above, the number 2 occurs 6 times and the number 3 occurs 5 times. 如果数字重复超过3次,我想将以下数字更改为1。因此在上面的向量中,数字2出现6次,数字3出现5次。 That means I want to replace the number 3 and 4 with 1. Ultimately in this snippet, the answer I'm looking for is: 这意味着我想将数字3和4替换为1。最终,在此代码段中,我正在寻找的答案是:

c(1,1,1,2,2,2,2,2,2,1,1,1,1,1,1,1)

What I have below worked for cases when only one number was repeated more than 3 times, but not multiple. 下面的内容适用于只有一个数字重复超过3次但不重复多次的情况。 In addition, if I'm doing this inefficiently I'd like to learn how to better script it. 另外,如果我的效率低下,我想学习如何更好地编写脚本。

stack <- table(vec1)
stack1 <- list(as.numeric(rownames(data.frame(stack[stack>3]))) + 1)
replace(vec1,vec1 == stack1,1)

thanks in advance for any help 预先感谢您的任何帮助

Try 尝试

inverse.rle(within.list(rle(vec1), 
      values[c(FALSE,(lengths >3)[-length(lengths)])] <- 1))
#[1] 1 1 1 2 2 2 2 2 2 1 1 1 1 1 1 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM