是否可以在不明确返回向量并替换旧向量的情况下更改R函数中的向量?我有以下功能模拟从牌组中抽出一张牌,我希望从牌组中取出牌,但以下内容不会改变。
Location currentLocation =
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
答案 0 :(得分:3)
危险的<<-
操作员似乎是你的朋友。它有环境复杂性,如果甲板在父环境中,这将起作用,但如果那里没有甲板,它将在更高和更高级别的环境中查找,直到它找到一个。
draw_card <- function(deck) {
card <- sample(deck, 1)
remove_card <- sample(which(deck==card))
deck <<- deck[-remove_card]
card
}
编辑:但是,如果你正在做这种OOP,我认为你应该看看R6类,你可以创建一个deck对象然后让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
答案 1 :(得分:2)
像
这样的东西## 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