-1

This is the function I'm trying to use:

x=10
y=10
mysample= function(n)
{
  z = runif(n,0,20)
  {
     if(x < z)
    {
      t = z
    } else 
    {
      t = x
    }
     data.frame(x,t)
  }
}

But then when I try:

A <- mysample(50)

It comes up with the warning message:

the condition has length > 1 and only the first element will be used

How do I fix this?

Catherine
  • 11
  • 1
  • 5
  • Welcome to SO! It would help if you specified what the warning message was. –  Apr 01 '18 at 09:41

1 Answers1

1

if should take only one TRUE/FALSE, while you asking it to check n.

x < z
 [1]  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE FALSE
[20] FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE
[39] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE

I think you want

set.seed(357)
z <- runif(50, min = 0, max = 20)
ifelse(x < z, z, x)

 [1] 10.00000 10.00000 10.00000 10.00000 13.06970 10.00000 18.67473 14.94917 15.56799 19.82682 12.49106 10.49149 10.00000
[14] 10.00000 11.79600 10.00000 10.00000 17.90611 13.66297 10.00000 10.00000 10.00000 10.00000 10.00000 14.15444 13.77288
[27] 10.00000 10.00000 10.32776 19.53836 10.00000 18.57790 10.00000 10.00000 11.40069 16.16679 13.86975 10.00000 16.86793
[40] 15.74069 10.00000 10.00000 12.99440 10.00000 10.00000 10.00000 10.44369 18.70916 10.00000 10.00000
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197