jeudi 5 janvier 2017

how to repeat 'for' loop when 'if' condition met using R

I am trying to replace 2 alphabets (repeats ) from vector of 26 alphabets. I already have 13 of 26 alphabets in my table (keys), so replacement alphabets should not be among those 13 'keys'. I am trying to write code to replace "C" & "S" by next present alphabet which should not be part of 'keys'. The following code is replacing repeat "C' by "D" and "S" by "T", but those both letters are in my 'keys'. Could someone know how I can implement condition so that code will re-run loop if letter to be replace is already present in 'key'? Thanks in advance /Swapnil

# alphabets <- toupper(letters)
keys <- c("I", "C", "P", "X", "H", "J", "S", "E", "T", "D", "A", "R", "L")
repeats <- c("C", "S")
index_of_repeat_in_26 <- which(repeats %in% alphabets)
# index_of_repeat_in_26 is 3 , 19
# available_keys <- setdiff(alphabets,keys)
available <- alphabets[available_keys]
# available <-  c("B", "F", "G", "K", "O", "Q", "U", "V", "W", "Y", "Z")
index_available_keys <- which(alphabets %in% available_keys)
# 2  6  7 11 15 17 21 22 23 25 26

for (i in 1:length(repeat)){
    for(j in 1:(26-sort(index_of_repeat_in_26)[1])){
        if(index_of_repeat_in_26[i]+j %in% index_available_keys){
            char_to_replace_in_key[i] <- alphabets[index_of_capital_repeat_in_26[i]+1]
        }
        else{
            cat("\n keys not available to replace \n")
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire