有条件地将向量的下一个元素附加到前一个元素

时间:2018-04-25 10:21:43

标签: r vector

我有一个具有多个值的向量。如果一个元素和下一个元素没有句点,我想用句号将下一个元素追加到前一个元素。但附加的元素不应再存在于载体

a = c("135","00","85","6","0.00","6","0.00","0.00","85","61","0.00")

我希望结果是

"135.00","85.6","0.00","6","0.00","0.00","85.61","0.00"

1 个答案:

答案 0 :(得分:1)

也许不是最优雅的,但这里有一个while构造的解决方案:

a <- c("135","00","85","6","0.00","6","0.00","0.00","85","61","0.00")

result <- character()
while(length(a) > 0) {

    ## pop first item from vector
    item <- a[1]
    a <- a[-1]

    ## if item contains dots, add to results
    if (grepl("\\.", item)) {
        result <- c(result, item)
    } else {        
        ## Otherise check if next item contains dot
        if (! grepl("\\.", a[1])) {
            ## if not, combine current and next item
            result <- c(result, paste(item, a[1], sep='.'))
            a <- a[-1]
        }
        else {
            ## otherwise return current item
            result <- c(result, item)
        }
    }    
}