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 !!

Amazon audibleの登録の紹介

プライム会員限定で2024年7月22日まで3か月無料体験キャンペーン開催中です。無料体験後は月額1,500円で聞き放題です。なお、聞き放題対象外の本はAudible会員であれば非会員価格の30%引きで購入することが可能です。

Amazon audibleはプロのナレーターが朗読した本をアプリで聞くことができるサービスで、オフライン再生も可能です。通勤や作業のお供にAmazon audibleのご登録はいかがでしょうか。

・AmazonのAudible

https://amzn.to/3L4FI5o

Copied title and URL