0

I used the following code

a=runif(15,0,1)
b=numeric(15)
for(i in 1:length(a))
{
  if(a[i]<(2/3))           
    b[i]=0
  else
    b[i]=1
}
b

Output

[1] 1 0 0 0 0 0 1 0 0 0 0 1 0 0 1

I tried modifying the if condition as follows

 a=runif(15,0,1)
b=numeric(15)
for(i in 1:length(a))
{
  if((1/3)<a[i]<(2/3))
    b[i]=0
  else
    b[i]=1
}
b

Output

    a=runif(15,0,1)
>     b=numeric(15)
>     for(i in 1:length(a))
+     {
+       if((1/3)<a[i]<(2/3))
Error: unexpected '<' in:
"    {
      if((1/3)<a[i]<"
>         b[i]=0
>       else
Error: unexpected 'else' in "      else"
>         b[i]=1
>     }
Error: unexpected '}' in "    }"
>     b
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

Can you please tell an alternative way how I can replace the values in specific range under vector by desired numeric like o.

1 Answers1

1

You can use lapply

a=runif(15,0,1)
b=numeric(15)

as.numeric(unlist(lapply(a, function(x) 1/3 < x & x < 2/3 )))

[1] 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0

Or you can also simply do

as.numeric(1/3 < a & a < 2/3)
[1] 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0
Hardik Gupta
  • 4,700
  • 9
  • 41
  • 83