简体   繁体   中英

Reorganizing a Vector with words in R

This is my vector:

myvector<-c("yes","yes","no","yes","yes","yes","No","No","No","yes","yes","No","No","No","yes","No","No","No","yes","yes")

I need to do the following:

if it has the word "no" repeatedly it deletes the first one and replace by "yes" the o others. He does it backwards . If the word "No" appears only once it doesnt do nothing.

The final vector should be like this:

myfinalvector<-c("yes","yes","no","yes","yes","yes","yes","yes","No","yes","yes","yes","yes","No","yes","yes","yes","No","yes","yes")

Any help guys?

You could use diff after coercing the rev erted vector to factor . "No" s where 0 and "No" occur simultaneously need to be replaced by "yes" .

d <- data.frame(x=c(NA, diff(as.numeric(factor(rev(myvector))))), y=rev(myvector))
d$y[d$y == "No" & d$x == 0] <- "yes"
as.character(rev(d$y))
# [1] "yes" "yes" "no"  "yes" "yes" "yes" "yes" "yes" "No"  "yes" "yes" "yes"
# [13] "yes" "No"  "yes" "yes" "yes" "No"  "yes" "yes"
ans = with(rle(r), unlist(lapply(seq_along(values), function(i){
    if (values[i] == "No" & lengths[i] > 1){
        c(rep("yes", lengths[i] -1), "No")
    } else {
        rep(values[i], lengths[i])
    }
})))

#OR

ans = ave(r, with(rle(tolower(r)), rep(seq_along(values), lengths)), FUN = function(x){
    if (length(x) > 1 & tolower(x[1]) == "no"){
        c(rep("yes", length(x) - 1), tail(x, 1))
    } else {
        x
    }
})

ans
# [1] "yes" "yes" "no"  "yes" "yes" "yes" "yes" "yes" "No"  "yes" "yes" "yes" "yes" "No"  "yes"
#[16] "yes" "yes" "No"  "yes" "yes"

You can use diff and select only the those No's that are the start of a sequence of no's:

# Find all no's:
all_nos = which(tolower(myvector)=="no")

# Only take the first in a list:
nos_to_keep = all_nos[diff(all_nos) > 1]

# Replace all non-desired no's with a "yes"
myvector[-nos_to_keep] = "yes"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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