lundi 9 juillet 2018

Why don't these two functions yield the same result?

I have these functions below.

sapply(1:3, function(i) {
  if (i %% 3 == 1) x <- 1
  if (i %% 3 == 2) x <- 2
  if (i %% 3 != 1 & i %% 3 != 2) x <- 0
  return(x)
})
# [1] 1 2 0

sapply(1:3, function(i) {
  if (i %% 3 == 1) x <- 1
  if (i %% 3 == 2) x <- 2
  else x <- 0
  return(x)
})
# [1] 0 2 0

I don't get why the two functions don't yield the same thing.

Aucun commentaire:

Enregistrer un commentaire