Kush Patel
Kush Patel

Reputation: 3855

How to use sample inside ifelse

I have following list

x = rep("a", 100)

and if i used following table

ifelse(x == "a", sample(c(1:100), 1), 0)

I get following output when I run first time.

[1] 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
[22] 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
[43] 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
[64] 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
[85] 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22

I am not able to see random sample between 1 and 100. How should I achieve it. I want randomness in output. Example of expected output is as follows:

  [1]   8  81  46  71  97  18  37  82  74  34  12   5  26   6  66  55
 [17]   2  84  68   9  29   7  38   4  64  90  39  54  75  45  20  42
 [33]  79  36  78  13  47  85  27  69  23  62  15  63  76  25  77  96
 [49]  98  11  53  83  30  41  91  43  88  28  65  10  49  99  56  67
 [65]  16  95  32  92  14  86  50  80  94  58  21  87  51  17  70   1
 [81]  33  57  59  73  52  22  31  44 100  61  60  35  89  24  48  72
 [97]  40  19   3  93

Upvotes: 5

Views: 1269

Answers (3)

Gregory Demin
Gregory Demin

Reputation: 4846

As mentioned above your sample generate only one number. To fix it your ifelse should be looks like this:

x = rep("a", 100)
ifelse(x == "a", sample(c(1:100), length(x)), 0)

or, if I correctly understand what do you want, even shorter version:

x = rep("a", 100)
ifelse(x == "a", sample(length(x)), 0)

If you want replace your "not a" value with sampling with replacement (each number can occurs several times) we finally get this code:

x = rep(c("a","b"), 50)
ifelse(x == "a", sample(length(x), replace = TRUE), 0)

Upvotes: 4

parksw3
parksw3

Reputation: 659

I tried to interpret your question:

x <- sample(c("a", "b"), 100, replace = TRUE)
res <- rep(0, length(x))
res[which(x == "a")] <- sample(length(x), sum(x == "a"), rep = TRUE)

Looking at ifelse(x == "a", sample(c(1:100), 1), 0), I'm guessing that what you want to do is this:

for(i in 1:length(x)){res[i] <- ifelse(x[i] == "a", sample(100, 1), 0)}

So it seemed like rep = TRUE was necessary. Also, x == "a" returns a TRUE/FALSE vector but it can also be converted to numeric vector by as.numeric(x == "a") to return 1/0 instead. Using sum without as.numeric still works and will return a number of elements in x that equal a.

Upvotes: 0

tobiasegli_te
tobiasegli_te

Reputation: 1463

I suspect ifelse runs sample() only once and returns this random value for each element where the condition is TRUE. You could instead use

sapply(x,function(y){
    ifelse(y == "a", sample(c(1:100), 1), 0)
})

Upvotes: 2

Related Questions