医科学のためのデータシミュレーション 1、のための予備知識

  • 医学・生物学データの扱いに慣れるために、データシミュレーションを中心に行うセミナーをするとして(医学研究科大学院コース ゲノム遺伝学@京大 2014:こちら)、それに参加するための最少要求内容のRmd
  • htmlファイルはこちら(Login as a guest でログインすると見られます)
  • こちらを参考にすればhtml化可能です
  • これに引き続き「関数、if、loop」をやります(こちら)
# Rを用いた医科学のためのデータシミュレーションの基礎 Basics of Data Simulation for Medical Sciene with R

## 基本のき ABC

### 起動と終了。Start and quit

q()

### コピー・ペースト Copy and paste

この文書のコマンドの部分は"Ctrl" + "c"でクリップボードにコピーできて、それを自分のRの上で"Ctrl" + "v"でペーストできる。
You can copy the commands on this page with "ctrl" + "c" and paste them onto your R window with "ctrl" + v.

ウィンドウズは"ctrl"+...で、Macはアップル+...

Windows: "ctrl" + ... but Mac: "Apple" + ...

テキストエディタ上にペーストすれば保存できる。
You can paste the commands on your text editor and you can save the commands as a file.

次のコマンドをコピー・ペーストして実行してみよ。

```{r}
boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
```

## データの扱い Handling of Data

### ベクトル Vectors

```{r}
v1 <- c(3,2.5,6)
# Length of vector = number of elements
length(v1)
v1.id <- 1:3
# Same
v1.id.1 <- 1:length(v1)
```

データを作ったらプロットする。Plot after you generate data.
```{r}
plot(v1)
plot(v1.id.1,v1)
```
プロットに少し情報を加える。Some information is added.
プロットを見比べて、どの指定が何をするかを確認する。Compare plots and understand which words determined which changes in the 2nd plot.
```{r}
plot(v1.id.1,v1,xlab="ID",ylab="value",main="test plot")
```

### 乱数列 Random number sequence
```{r}
# Length
n <- 100
v2 <- runif(n) # 0-1の一様乱数 random values in uniform distribution from 0 to 1
v2
```
プロットして理解する。Grab what they are by plotting them.
```{r}
plot(v2)
# ソートするとわかりやすい Sorted sequence might be more informative 
sorted.v2 <- sort(v2)
# 逆順にもソートできる Sorting in descreasing order is also useful.
inv.sorted.v2 <- sort(v2,decreasing=TRUE)
plot(sorted.v2)
plot(inv.sorted.v2)
```

### Help記事と検索 Help article and serching information

関数を知っていてその使い方を知りたいとき。When you know name of functions and you want to know how to use them.
```{r}
help(length)
help(runif)
```

キーワードを知っていてそれに関連する記事を検索したいとき。
When you know keywords and search related articles.
用語の一部を知っているとき。When you can spell a part of terms.

```{r}
?? "length"
?? "uniform"
apropos("chi")
```
### 正規乱数
正規乱数はもう一つの基本。Random numbers in normal distribution are important, too.
```{r}
v3 <- rnorm(n)
plot(v3)
sorted.v3 <- sort(v3)
inv.sorted.v3 <- sort(v3,decreasing =TRUE)
plot(sorted.v3)
plot(inv.sorted.v3)
# 分布のプロット Distribution plot
hist(v3)
plot(density(v3))
boxplot(v3)
# 記述統計する Descriptive statistics.
summary(v3)
```

### データフレーム Data frames : 複数のベクトルの束 Bundle of multiple vectors

2つのベクトルを併せる。Combine two vectors.
```{r}
n <- 20
v4 <- runif(n)
v5 <- sample(c("male","female"), n, replace = TRUE)
df1 <- data.frame(value=v4, sex=v5)
df1
```
プロットしてみる。 Plot the data.frame.
```{r}
plot(df1)
```

追加する。Add vecors.
```{r}
v6 <- rnorm(n)
v7 <- sample(1:4, n, replace = TRUE)
df2 <- data.frame(df1, x = v6, y = v7)
df2
plot(df2)
boxplot(df2)
summary(df2)
```

## 行列 Matrix

すべての項目が数値を持つなら行列の方が便利かもしれない。線形代数処理など。プロットも違うタイプのものがある。When all values are numeric, matrix rather than data frame might be useful. For example, application of linear algebra to it. Different kind of plots are also available.

```{r}
# sex "male","female" are changed into 0,1
v5.num <- sample(0:1,n,replace=TRUE)
m1 <- cbind(v4,v5.num,v6,v7)
m1
plot(as.data.frame(m1))
image(m1)
matplot(m1,type="l")
persp(m1)
```

行列には行ごとの操作と列ごとの操作をすることができる。You can apply a function to each rows or each columns of matrix.
```{r}
m2 <- matrix(c(1,2,3,4,5,6),2,3)
m2
apply(m2,1,sum)
apply(m2,2,max)
```

## リスト List

長さが揃っていないものとまとめる。
When you want to put multiple things that are different in their length, use list.

```{r}
x <- 1:3
y <- 1:4
L <- list(x,y)
L
L[[1]]
L[[2]]
L$x
L$y
L1 <- list(x=x,y=y)
L1[[1]]
L1[[2]]
L1$x
L1$y
```
## テキストファイルの読み書き Read/Write text files

いくつかのオプションがありますが、一つを覚えて使いまわします。
There are multple ways to do but start using one way and in case you really need expand your skills on this.

ファイルのハンドリングをするためには、コンピュータ上でのRの作業場所を確認したり変更したりする必要があります。

When you handle text files on your computer, you should check where you use R on your computer and be able to move to where you want to go.

```{r}
# working directory : wd
apropos("wd")
getwd()
help(setwd)
```

RのGUIを使っているならツールバーからディレクトリ変更をすることができるはず。
If you are using R's RUI, you can change your working directory though its toolbars menu.

さて、ファイルのハンドリング。
Let's start handling your textfiles.

エクセル等のスプレッドシートアプリケーションを使って、数行、数列の数値ばかりのシートを作り、それをタブ区切りテキストファイルで保存時ます。たとえば"mydata.txt"という名前で。

Open excel or similar spread-sheet application and fill a rectangle area with several rows x several columns.
Save the sheet as a tab-delimitated text file, for example with name of "mydata.txt".

```{r}
mydata <- read.table("mydata.txt")
mydata
```

すでに作った行列m1を"m1.txt"という名前で保存してみます。
Let's save the matrix, m1, as a text file "m1.txt".

```{r}
write.table(m1,"m1.txt")
```

## 練習問題 Exercises
* 以下の問題のコマンドをテキストファイルで保存して提出せよ。Save your commands for the following exercises and report the file.
 * Q x軸とy軸のラベルと図のタイトルとを適当な語にして散布図を描け。Draw a coplot with its x-axis and y-axis labels as well as title being what you like.
 * 乱数は分布に従って発生させる。一様分布乱数、正規分布乱数、ポアソン分布乱数、指数分布乱数、ベータ分布乱数のヘルプ記事を表示し、そのExamplesを実行せよ。When you generate random numbers, you need distributions. Open help articles on uniform, normal, poisson, exponential and beta distributions and run the example codes.
 * sample()関数のオプションreplace=TRUEとreplace=FALSEの違いをヘルプ記事で確認し、次のコードが実行することを、言葉で説明せよ。エラーメッセージの異同についても確認すること。そしてその異同の理由についても説明すること。Check help article of sample() for the option relace = TRUE or FALSE and describe what the following codes do. Pay attention to the error messages and check the presence of difference and describe the difference/lack of difference.
 ```{r}
 sample(1:10)
 sample(1:10,8)
 sample(1:10,8,replace=TRUE)
 sample(1:10,8,replace=FALSE)
 sample(1:10,12)
 sample(1:10,12,replace=TRUE)
 sample(1:10,12,replace=FALSE)
 ```
 * 3列のデータフレームを適当に作成せよ。Make 3 column-data frame as you like.
 * 75列の整数を要素とする行列を作り、各列の平均要素とするベクトルを作れ。また各行の最小値を要素とするベクトルを作れ。Generate a 7-row 5-column-matrix (7x5 matrix). Make a vector whose elements are mean of each columns of the matrix. Make a vector whose elements are minimum value of each rows of the matrix.