簡體   English   中英

如何從R中的函數中刪除向量的元素

[英]How to remove an element of a vector from within a function in R

是否可以在R函數中更改向量而無需顯式返回向量並替換舊的向量? 我有以下功能,可以模擬從卡組中抽出一張卡片,我希望從卡組中取出抽出的卡,但是下面的操作不會改變。

draw_card <- function(deck) {
  card <- sample(deck, 1)
  remove_card <- sample(which(deck==card))
  deck[-remove_card]
  card
}

看來危險的<<-操作員是您的朋友。 但是,它具有環境復雜性,如果甲板位於父環境中,則可以使用,但是如果那里沒有甲板,它將在越來越高的環境中尋找,直到找到一個為止。

draw_card <- function(deck) {
  card <- sample(deck, 1)
  remove_card <- sample(which(deck==card))
  deck <<- deck[-remove_card]
  card
}

編輯:但是,如果您正在執行這種OOP,我想您應該看一下R6類,可以創建一個甲板對象,然后讓draw_card是一種通過引用更新甲板的方法

例如,這是一個R6類,它可以滿足您的需求:

library(R6)
deck <-
 R6Class('deck',
      public = 
        list(
          cards = list(),
          initialize =
            function(cards) {
              self$cards <- cards
            },
          drawCard =
            function() {
              card <- sample(self$cards,1)
              self$cards <- setdiff(self$cards,card)
              card
            }
        ))

 #Make a new object with:
 newDeck <- deck$new(1:52)
 #Start Drawing Cards
 newDeck$drawCard()
 newDeck$drawCard()
 # Check remaining deck, notice the cards you've drawn are missing:
 newDeck$cards

怎么樣

## initialise the deck
deck <- 1:52

## remove a random card from the deck
set.seed(123)
deck <- deck[-sample(deck, 1)]
## or, if you're not using 1:52
## deck <- deck[deck != deck[sample(deck, 1)] ]

## record which cards have been removed
removed_card <- 1:52[!1:52 %in% deck]

deck
# [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
# [40] 41 42 43 44 45 46 47 48 49 50 51 52

removed_card
# [1] 15

暫無
暫無

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

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