搜索不在列表中的下一个最接近的元素

时间:2017-01-05 19:30:03

标签: r if-statement for-loop

我正在尝试从26个字母的向量中替换2个字母(重复)。

我的桌子中已经有26个字母中的13个(键),因此替换字母不应该在那些13键中#39;

我正在尝试编写代码以将C & S替换为下一个现有字母,而该字母不应该是'键的一部分。

以下代码正在替换重复C by DS by T,但这两个字母都在我的'键中。有人可以知道如何实现条件,以便代码将重新运行循环,如果要替换的字母已经存在于'键'?

# 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")
        }
    }
}

1 个答案:

答案 0 :(得分:1)

keys <- c("I", "C", "P", "X", "H", "J", "S", "E", "T", "D", "A", "R", "L")
repeats <- c("C", "S")

y = sort(setdiff(LETTERS, keys))       # get the letters not present in 'keys' 
y = factor(y, levels = LETTERS)        # make them factor so that we can do numeric comparisons with the levels
y1 = as.numeric(y)                     # keep them numeric to compare
z  = factor(repeats, levels = LETTERS)
z1 = as.numeric(z)

func <- function(x) {         # so here, in each iteration, the index(in this case 1:4 gets passed)
           xx = y1 - z1[x]    # taking the difference between each 'repeat' element from all 'non-keys'
           xx = which(xx>0)[1]# choose the one with smallest difference(because 'y1'  is already sorted. So the first nearest non-key gets selected
           r = y[xx]          # extract the corresponding 'non-key' element            
           y <<- y[-xx]       # after i get the closest letter, I remove that from global list so that it doesn't get captured the next time
           y1 <<- y1[-xx]     # similarily removed from the equivalent numeric list
           r                  # return the extracted 'closest non-key' chracter 
 }

 # sapply is also a for-loop by itself, in which a single element get passed ro func at a time. 
 # Here 'seq_along' is used to pass the index. i.e. for 'C' - 1, for 'S' - 2 , etc gets passed.

 ans = sapply(seq_along(repeats), func)

if (any(is.na(ans))){
  cat("\n",paste0("keys not available to replace for ",
           paste0(repeats[which(is.na(ans))], collapse = ",")) ,
      "\n")
  ans <- ans[!is.na(ans)]
}
# example 2 with :
repeats <- c("Y", "Z")
# output : 
# keys not available to replace for Z 
# ans
# [1] Z

注意:要了解sapply()的每个版本如何运作:您应该运行debug(func)然后运行sapply()调用。然后,您可以在控制台上检查每个变量xxr的评估方式。希望这可以帮助!