裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

複数のオブジェクトの要素を順に関数の引数にする

2014年08月17日 | ブログラミング

http://minato.sip21c.org/standardbodyweight.R
「Rの関数定義と計算
において,

中澤さんが,「つい Vectorize() を使ってしまうのだが,本当はもっと正統派なやり方があるんだろうなあ。」と書いている。
正統派かどうか分からないが,以下のように,mapply() を使うのも一法かと。
Vectorize は使ったことがなかったのだけど,関数定義を見たら,なあんだ,mapply() を使うためのラッパーなんだ。

なお,計算に使う係数は,行列などにしておき,性別や年齢を添え字にして引用するようにすると,プログラムが分かりやすくなる(と思う。LibreOfficeの場合も同じと思う。)。

# Calculation of standard body weights, obesity degree (%), and BMI
# based on the method of Japanese School Health Statistics
# http://www.mext.go.jp/component/b_menu/other/__icsFiles/afieldfile/2013/03/29/1331750_3.pdf
# (C) Minato Nakazawa, Ph.D. 13 August 2014

Age = c(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)
# Ba, Ga
a = cbind(c(0.386, 0.461, 0.513, 0.592, 0.687, 0.752, 0.782, 0.783, 0.815, 0.832, 0.766, 0.656, 0.672),
          c(0.377, 0.458, 0.508, 0.561, 0.652, 0.73, 0.803, 0.796, 0.655, 0.594, 0.56, 0.578, 0.598))
# Bb, Gb
b = cbind(c(23.699, 32.382, 38.878, 48.804, 61.39, 70.461, 75.106, 75.642, 81.348, 83.695, 70.989, 51.822, 53.642),
          c(22.75, 32.079, 38.367, 45.006, 56.992, 68.091, 78.846, 76.934, 54.234, 43.264, 37.002, 39.057, 42.339))

stwt = function(age, sex, height) {
 age = age-4
 a[age, sex]*height-b[age, sex]
}

# stwtv = Vectorize(stwt)

# Definition of a sample data
sampledata = data.frame(
 Age = c(7, 11, 17, 11, 14, 17),
 Sex = c(1, 1, 1, 2, 2, 2), # 1: Boy, 2: Girl
 Height = c(115, 155, 185, 150, 150, 150),
 Weight = c(20, 46, 71, 50, 50, 50))

# Calculation
sampledata$StandardWt = mapply(stwt, sampledata$Age, sampledata$Sex, sampledata$Height)
sampledata$Obese = (sampledata$Weight - sampledata$StandardWt)/sampledata$StandardWt*100
sampledata$BMI = sampledata$Weight/(sampledata$Height/100)^2

print(sampledata)

 

 

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村