Analysis in R: Iteration and conditional decision commands

RAnalytics
スポンサーリンク

The R operation combines commands to process data and output results. In many cases there is rarely a single element in the data, but rather several elements, and each element is processed repeatedly and the results are output. Therefore, repetition and conditional evaluation commands are introduced here.

スポンサーリンク

Repeat the command: for ( element in the number of processes ) {process}

The “for” command repeats the number of times the element (often set to a single letter, such as i, m, etc. in alphabetical order) inside the parentheses will be processed. For example, here is a code that outputs a sequence of numbers from 1 to 7, adding 3 to each.

data <- c(1, 2, 3, 4, 5, 6, 7)

for (i in seq(data)) {
   cat(i + 3, "\n")
}

#Result
4
5
6
7
8
9
10

Note that the “in” is followed by “seq(data)” to get the repeated range. “1:7” is also acceptable, but specifying the range by the length of the data to be processed rather than by a number will reduce errors.

Command for conditional judgment: if (condition) {process 1} else {process 2}

The “if else” command executes process 1 if the condition is true and process 2 if it is not. For example, here is code that outputs a sequence of numbers from 1 to 7, adding 3 only to even numbers.

data <- c(1, 2, 3, 4, 5, 6, 7)

for(i in seq(data)){
  
  if (i%%2 == 0){
    
    cat(i + 3, "\n")
    
  }else{
    
    #If odd, do not process. Blank
    
  } 
  
}

#Result
5
7
9

It can also be processed simply as ifelse(condition, process 1, process 2). However, since NA is included in the result, some processing ingenuity is required.

ifelse(data%%2 == 0, data + 3, NA)

#Result
[1] NA 5 NA 7 NA 9 NA

I hope this makes your analysis a little easier !!

Copied title and URL