dta <- read.table("hs0.txt", header=T)
#
dta.asian <- subset(dta, race=="asian")
r0 <- cor(dta.asian$math, dta.asian$socst)
cnt <- 0
nIter <- 1001
for (i in 1:nIter) {
new <- sample(dta.asian$read)
r <- cor(new, dta.asian$math)
if ( r0 <= r ) cnt <- cnt+1
}
cnt/nIter
## [1] 0.03196803
#
改為
i=1
cnt=0
repeat{
new <- sample(dta.asian$read)
r <- cor(new, dta.asian$math)
i=i+1
if ( r0 <= r ) cnt <- cnt+1
if (i>=nIter)
break
}
cnt/nIter
## [1] 0.04195804
每次隨機的x,y的散布圖,照nIter設置的數量產生出多少張圖
Brownian <- function(n = 5, pause = 0.05, nIter = 1, ...) {
x = rnorm(n)
y = rnorm(n)
i = 1
repeat {
plot(x, y, ...)
text(x, y, cex = 0.5)
x = x + rnorm(n)
y = y + rnorm(n)
Sys.sleep(pause)
i = i + 1
if(i >= nIter) break
}
}
Brownian(xlim = c(-20, 20), ylim = c(-20, 20),
pch = 21, cex = 2, col = "cyan", bg = "lavender")
改repeat
Brownian <- function(n = 11, pause = 0.05, nIter = 512, ...) {
x = rnorm(n)
y = rnorm(n)
i = 1
repeat {
plot(x, y, ...)
text(x, y, cex = 0.5)
x = x + rnorm(n)
y = y + rnorm(n)
Sys.sleep(pause)
i = i + 1
if (i>=nIter)
break
}
}
使用ifelse調整m矩陣
library("magrittr")
## Warning: package 'magrittr' was built under R version 3.4.4
newsim<- function(n){
m <- matrix(nrow=n, ncol=2)
m[, 1] <- runif(n)
m[, 2] <- rnorm(n)
Gender <- ifelse(m[, 1]<0.5, "M", "F")
Height <- ifelse(m[, 1]<0.5, 170 + 7*m[, 2],160 + 5*m[, 2]) %>% round(2)
Person <- data.frame(Gender,Height)
return(Person)
}
newsim(10)
## Gender Height
## 1 F 165.66
## 2 F 153.11
## 3 F 168.60
## 4 F 160.81
## 5 F 153.15
## 6 M 159.76
## 7 F 171.05
## 8 M 171.02
## 9 M 163.56
## 10 M 169.13