Ifelse() with three conditions

前端 未结 3 1527
萌比男神i
萌比男神i 2021-01-01 18:46

I have two vectors:

a<-rep(1:2,100)

b<-sample(a)

I would like to have an ifelse condition that compares each value of a

相关标签:
3条回答
  • 2021-01-01 19:17

    How about adding another ifelse:

    ifelse(a>b, 1, ifelse(a==b, sample(1:2, length(a), replace = TRUE), 0))
    

    In this case you get the value 1 if a>b, then, if a is equal to b it is either 1 or 2 (sample(1:2, length(a), replace = TRUE)), and if not (so a must be smaller than b) you get the value 0.

    0 讨论(0)
  • 2021-01-01 19:23

    This is an easy way:

    (a > b) + (a == b) * sample(2, length(a), replace = TRUE)
    

    This is based on calculations with boolean values which are cast into numerical values.

    0 讨论(0)
  • 2021-01-01 19:26

    There is ambiguity in your question. Do you want different random values for all indexes where a==b or one random value for all indexes?

    The answer by @Rob will work in the second scenario. For the first scenario I suggest avoiding ifelse:

    u<-rep(NA,length(a))
    u[a>b] <- 1
    u[a<b] <- 0
    u[a==b] <- sample(1:2,sum(a==b),replace=TRUE)
    
    0 讨论(0)
提交回复
热议问题