Kppatel Patel Kppatel Patel - 1 month ago 7
R Question

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

Answer

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)