loops - Assigning variables within the ifelse function in r -
i pretty new r , trying better grasp of language solving problems 1 of books r (i not sure if can put title here not advertise it). 1 of problems asking conditional assigning values variables, based on criteria. more precise, randomly choosing number between 2 , 12 (throwing 2 dice) , dependently on value get, have assign values variables status , points follows:
- if score 2,3, or 12
status <- false,points <- na - if score 7 or 11
status <- true,points <- na - if score 4-6,8-10
status <- na,points <- score
it quite simple problem , know following code works:
score <- sample(2:12,1) if(score %in% c(2,3,12)){ status <- false points <- na } else if(score %in% c(7,11)){ status <- true points <- na } else { status <- na points <- score } i trying solve problem using ifelse function error when try assign variables. here did (i know right character vector way make 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 way assign values within ifelse function? also, can done switch function? trying figure out if there more 1 way solve simple problem know how proceed more complicated ones.
thank you!
this may not elegant answer demonstrates use of ifelse conditional statements:
status=null status[score %in% c(2,3,12)]<-false status[score %in% c(7,11)]<-true status[score %in% c(4:6,8:10)]<-na points=ifelse(score %in% c(4:6,8:10),score,na) as can see, used ifelse create logical statement points first argument logical test, second argument replaces value of score if true , last replaces value if false.
Comments
Post a Comment