0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rで第一・第三四分位数を求めるテンプレート

Last updated at Posted at 2020-02-14
tags: rBasicLearning

四分位数

1. 四分位数を求めるテンプレート

四分位数を求めるテンプレートは, 以下に作りました.
宜しければ, 使ってください!

  1. データの大きさの剰余で奇数か偶数かの分岐をif文で作ります
  2. 前半のデータをデータの大きさの整数商で分けます(整数商にするのは, データの大きさが奇数でも偶数でも変わらないようにするためです)
  3. 前半・後半のデータを取り出します(後半のデータは前半のデータを取り除く形で表しています)
  4. 前半・後半のデータの中で中央値を取ります
Q1Q3 = function(x) {
  n = length(x)
  if (n %% 2 == 0) {
    firstHalf <- n %/% 2
    firstHalfData <- x[1:firstHalf]

    latterHalfData <- x[-(1:firstHalf)]
  } else {
    firstHalf <- n %/% 2
    firstHalfData <- x[1:firstHalf]
    
    latterHalfData <- x[-(1:(firstHalf + 1))]
  }
  return(c(Q1 = median(firstHalfData), Q3 = median(latterHalfData)))
}

2. 具体例

使うデータ

今回は, 奇数の大きさのデータ(oddData)と
偶数の大きさのデータ(evenData)を使います

oddData <- c(62, 64, 65, 67, 67, 68, 70, 73, 77, 80, 82)
evenData <- c(18, 20, 21, 23, 23, 25, 27, 29, 30, 31, 32, 39)

データの具体例

oddData <- c(62, 64, 65, 67, 67, 68, 70, 73, 77, 80, 82)
Q1Q3(oddData)

evenData <- c(18, 20, 21, 23, 23, 25, 27, 29, 30, 31, 32, 39)
Q1Q3(evenData)

データの出力

> evenData <- c(18, 20, 21, 23, 23, 25, 27, 29, 30, 31, 32, 39)
> Q1Q3(evenData)
  Q1   Q3 
22.0 30.5 
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?