How To Use Conditional Statements in R?

sortinoIndex is a vector that contain NA and numeric numbers I want create a loop to extract only the numeric numbers and save them into sortino1 how can I do? I did this but does not work can you help me?

    sortino1<-numeric()
for (i in 1:252) {
  if(sortinoIndex[i]!=NA){
    sortino1[i]<-sortinoIndex[i]
  }
}

2 answers

  • answered 2018-11-12 19:27 Mako212

    In R, we typically won't use a for loop to do something like this, because it is very slow compared to implementing the same loop in C++.

    Instead, we'll use a vectorized operation:

    Create some data:

    set.seed(10)
    sortinoIndex <- sample(c(NA,1:10),25, replace = TRUE)
    

    Remove NA values:

    sortino1 <- sortinoIndex[!is.na(sortinoIndex)]
    print(sortino1)
    
    [1] 5 3 4 7 2 3 2 6 4 7 6 1 6 3 4 2 4 9 9 6 8 3 4
    

  • answered 2018-11-12 19:28 akrun

    We can use complete.cases

    sortinoIndex[complete.cases(sortinoIndex)]