I'm trying to write a function (or the best R alternative), given a deck vector and a hand vector, that takes the first element from the deck and adds it to the hand.
# initialize the deck. We don't care about suits, so modulus 13
deck <- sample(52, 52, replace = FALSE, prob = NULL) %% 13 + 1
# initilize the hand
hand <- vector(mode="numeric", length=0)
#deal a card from the deck to the hand.
# it's these two lines I'd like to put in something like a function
# and return the modified vectors
phand <- c(hand, deck[1])
deck <- deck[-1]
In something like Python, you might do it like this:
def dealcard(deck,hand)
# do something to deck and hand
return deck, hand
deck,hand = dealcard(deck,hand)
Looking at the first answer to this: modify variable within R function
There are ways as @Dason showed, but really - you shouldn't!
The whole paradigm of R is to "pass by value". @Rory just posted the normal way to handle it - just return the modified value...
So what is the most R-thonic way to accomplish this "modifying multiple arguments to a function"?
I could see accomplishing something similar with a matrix where one column uses numbers to indicate which hand a row/card is dealt to, but it would make the code much less intuitive. It's easy to imagine a function:
score <- ScoreFunction(DealerHand)
vs.:
score <- ScoreFunction(DeckMatrix, 1)