I am pretty new to r and I am trying to get a better grasp of this language by solving problems from one of the books about r (I am not sure if I can put the title here to not advertise it). One of the problems is asking for conditional assigning values to variables, based on certain criteria. To be more precise, I am randomly choosing a number between 2 and 12 (throwing 2 dice) and dependently on the value I get, I have to assign values to variables status
and points
as follows:
- if score is 2,3, or 12 then
status <- FALSE
andpoints <- NA
- if score is 7 or 11 then
status <- TRUE
andpoints <- NA
- if score is 4-6,8-10 then
status <- NA
andpoints <- score
It is quite simple problem and I know that the following code works (`score is :
score <- sample(2:12,1)
if(score %in% c(2,3,12)){
status <- FALSE
points <- NA
} else if(score %in% c(7,11)){
status <- FALSE
points <- NA
} else {
status <- FALSE
points <- NA
}
I was also trying to solve this problem using the ifelse
function but I get an error when I try to assign variables. Here is what I did (I know that what I get right now is a character vector but that was the only way I could make it work).
ifelse(any(score == c(2,3,12)), "game_status = FALSE, point = NA",
ifelse(any(score == c(7,11)), "game_status = TRUE, point = NA",
paste("game_status = NA, point = ", score)))
Is there a way to assign values within the ifelse
function? Also, can it be done with the switch
function? I am trying to figure out if there is more than just one way to solve this simple problem so that I know how to proceed with more complicated ones.
Thank you!
Aucun commentaire:
Enregistrer un commentaire