Ex: Computing a vector of logicals that is true when x[i]>0

Viewed 31

With x a vector of numbers, write code in R to compute a vector y of logicals such that y[i] is TRUE whenever x[i] > 0.

I tried to answer in the following way:

x<-c(-1,0,1,2)
y<-logical(length(x))

for (i in 1:length(x)){
  y[i]-x[i]>0
  
 }

But it is printing a vector y of everything false.

If I try:

y-x>0

It does not work either.

Question:

How should I solve this apparently simple problem?

Thanks in advance!

1 Answers

Long but hopefully easy to understand.

for(i in 1:length(x)){

  if(x[i] > 0){
    y[i] <- TRUE

  } else {
    y[i] <- FALSE
  }
}
Related