1

我正在编写一个函数,它从一副牌中随机选择 10 张牌,然后我必须计算红桃花色中有多少张牌。我坚持使用 substr(),因为我们被告知它可以帮助我们,但我不知道如何正确使用它。

卡片向量是

cards <- 
  paste0(c("A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"),
         rep(c("H", "C", "S", "D"), each = 13))

以及我到目前为止所做的

drawCard <- function(x){
  
 x <- sample(cards, x, replace = F)
  
  
 print(x)
 

 heartCount <- length(substr((" H"),2,2))
 
 print(heartCount)
 

}


drawCard(10)


它在全球范围内有效,但我似乎无法针对我随机选择的卡片。

4

1 回答 1

1

这会给你想要的。我将您的函数修改为具有两个参数dfnsample. 这个想法是您首先substr是样本卡的第二个字符,然后您需要检查它们是否为“H”(==)。最后,sum用来计算有多少是“H”。

drawCard <- function(df, nsample){
  sample <- sample(df, nsample, replace = F)
  heartCount <- sum((substr(sample, 2, 2) == "H"))
  # print(sample) 
  return(heartCount)
}

drawCard(cards, 10)
于 2021-02-09T05:49:55.583 回答