本文へスキップ
からだにいいもの

Rのトピックスを中心に『まだ、まだ、知らない、役に立つ情報?』を発信します。

Analysis in R: Iteration and conditional decision commands

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から提供されたものであり、更新または削除される場合があります。
karada-goodはAmazonアソシエイトとして、適格販売により収入を得ています。