jeudi 5 août 2021

if and ifelse in R, multiple element used & nest failed

I recently started with r, and I got problems with if and ifelse.

here is what I tried

two_d6 <- function(n)
{
  random_numbers <- matrix(
    sample(6, 2 * n, replace = T),
    nrow = 2
  )
  colSums(random_numbers)
}  

this is a function to generate random numbers, no problem with it


scores <- two_d6(10)

for(i in 1:length(scores))
{ 
 
  if(scores[i] %in% c(2,3,12))
{
  game_statues <- F
  point <- NA
} else if(scores[i] %in% c(7,11))
{ 
  game_statues <- T
  point <- NA
} else
{
  game_statues <- NA
  point <- scores
}
}
game_table <- data.frame(game_statues = game_statues, point = point, 
                         score = scores) ; game_table


   game_statues point score
1            NA    10    10
2            NA     7     7
3            NA    10    10
4            NA     9     9
5            NA     7     7
6            NA     5     5
7            NA     5     5
8            NA    11    11
9            NA     7     7
10           NA     4     4 

it doesn't work, seems only the final "else" part worked.

Then I tried:

ifelse(scores %in% c(2,3,12), ((game_statues <- F) & (point <- NA)), 
       ifelse(scores %in% c(7,11), ((game_statues <- T) & (point <- NA)),  
             ((game_statues <- NA ) & ( point <- scores))))

 [1]    NA    NA    NA    NA    NA FALSE    NA    NA    NA    NA

game_table <- data.frame(game_statues = game_statues, point = point, 
                         score = scores) ; game_table

   game_statues point score
1            NA     8     8
2            NA     9     9
3            NA     7     7
4            NA     8     8
5            NA     6     6
6            NA     2     2
7            NA     8     8
8            NA    10    10
9            NA     7     7
10           NA     4     4



it seems the same reason with if function.

I can't see what's wrong. Could you please tell me how to improve it with these two functions and get the right table? THX!

Aucun commentaire:

Enregistrer un commentaire