簡體   English   中英

R 采樣字母(字母)時如何檢查下一個字母是否比前一個字母更大?

[英]R when sampling letters (LETTERS) how do I check if the next letter is a greater letter value then the previous one?

我需要繼續打印(繪制)字母,直到下一個字母與前一個字母順序不同。

一個例子是 CDEA,因為 A 不在 E 之后,所以抽獎次數為 4。我正在嘗試使用 while 循環來執行此操作。

draw <- function() {

   drawletters <-  sample(LETTERS)
   drawnum <- 0


   while (drawletters > drawletters) {
      firstdraw <- drawletters
      drawletters <- sample(LETTERS)
      drawnum <- drawnum + 1
    }

   print(drawletters)

}

我了解我的條件語句在我的循環中是如何錯誤的,但我不知道 go 的最佳方法。

這是一種潛在的解決方案:

# Create an empty (NULL) vector to store the results of each run
results <- c()

# Create the function
draw <- function(){
  # Start with draw_num = 0
  draw_num <- 0
  # Draw a letter
  firstdraw <- sample(LETTERS, 1)
  # Add 1 to draw_num
  draw_num <- draw_num + 1
  # Draw another letter
  nextdraw <- sample(LETTERS, 1)
  # Add another 1 to draw_num
  draw_num <- draw_num + 1
  # Print the letters (you can omit this if you don't need it)
  print(firstdraw)
  print(nextdraw)
  # Then use a while loop to print the letters and add 1 to draw_num
  # until the next letter comes before the previous
    while(nextdraw > firstdraw) {
      firstdraw <- nextdraw
      nextdraw <- sample(LETTERS, size = 1)
      draw_num <- draw_num + 1
      print(nextdraw)
    }
  # Then print draw_num
  print(draw_num)
  # And append draw_num to the results vector
  results <<- c(results, draw_num)
}

# Run the function a bunch of times (e.g. run "draw()" 10X)
draw()


# Then you can see the average number of letters drawn across all runs
mean(results)
#>[1] 2.7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM