简体   繁体   English

R编程:这个for循环的更灵活的版本

[英]R programming: more flexible version of this for loop

Below is my R code that takes vector a and returns vector b. 下面是我的R代码,它采用向量a并返回向量b。 Vector b is supposed to be a unique identifier of vector a with a particular format. 向量b应该是具有特定格式的向量a的唯一标识符。 Note that a is sorted with all the same numbers next to each other. 请注意,a使用彼此相邻的所有相同数字进行排序。

a <- c(1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8, 9, 9)
b <- NULL


for(i in 5:length(a)){
        if (a[i] == a[i - 1] & a[i] == a[i - 2] & a[i] == a[i - 3] & a[i] == a[i - 4])
            b[i] <- paste(a[i], "-", 4, sep="")
        else if (a[i] == a[i - 1] & a[i] == a[i - 2] & a[i] == a[i - 3])
            b[i] <- paste(a[i], "-", 3, sep="")
        else if (a[i] == a[i - 1] & a[i] == a[i - 2])
            b[i] <- paste(a[i], "-", 2, sep="")
        else if (a[i] == a[i - 1])
            b[i] <- paste(a[i], "-", 1, sep="")
        else 
            b[i] <- paste(a[i], "-", 0, sep="")
}

#The first 4 values in vector b have to manually entered 
#because the for loop checks up to 4 consecutive numbers in a
b[1] <- "1-0" 
b[2] <- "1-1"
b[3] <- "1-2"
b[4] <- "2-0"

b

The above code returns b as needed, however, if vector a has more than 4 consecutive numbers that are the same, then the for loop would yield b that contains some elements that are the same. 上面的代码根据需要返回b,但是,如果向量a具有多于4个相同的连续数,则for循环将产生包含一些相同元素的b。 How can this for-loop be improved such that any amount of the same consecutive numbers can be given the appropriate unique identifier. 如何改进这种for循环,以便可以为任何数量的相同连续数字赋予适当的唯一标识符。

I'm thinking of using some sort of nested for-loop but how can this be done inside an if statement? 我正在考虑使用某种嵌套的for循环,但是如何在if语句中完成呢?

This could probably replace your current loop. 这可能会取代您当前的循环。 rle() is used to construct a sequence for each unique element of a , starting from zero. rle()被用于构建序列的每个唯一元件a ,从零开始。 Then we can paste() them together with a - separator. 然后我们可以将它们与-分隔符paste()在一起。

paste(a, sequence(rle(a)$lengths) - 1, sep = "-")
#  [1] "1-0" "1-1" "1-2" "2-0" "2-1" "2-2" "3-0" "4-0" "5-0" "6-0" "6-1"
# [12] "6-2" "6-3" "7-0" "8-0" "9-0" "9-1"

which is identical to your output from b 这与b的输出相同

Using ave and paste , which I now realise is essentially just a variation on @RichardScriven's answer: 使用avepaste ,我现在意识到这基本上只是@ RichardScriven答案的变体:

paste(a, ave(a,a,FUN=seq_along) - 1, sep="-")
# [1] "1-0" "1-1" "1-2" "2-0" "2-1" "2-2" "3-0" "4-0" "5-0" "6-0" "6-1"
#[12] "6-2" "6-3" "7-0" "8-0" "9-0" "9-1"
# If you are sure the different groups are really sorted, this will work:
b <- tapply(1:length(a), a, FUN = function(x) (1:length(x)) -1 )
b <- paste(a, unlist(b), sep = "-")

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

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