軟體下載
• Google 搜尋“R” 第一個顯示即是R統
計軟體網頁
• The R Project for Statistical
Computing
• CRAN
• 選擇下載點
:http://cran.csie.ntu.edu.tw/
• Windows baseR-3.0.0-win32.exe
vectors(1)
> a =rnorm(100, mean = 50, sd = 5)
> str(a)
num [1:100] 49.2 48.7 46.1 43.9 44.3 ...
> head(a) ### 列出前面六項
[1] 49.17096 48.71730 46.13608 43.89396 44.28375 43.36800
> tail(a) ### 列出最後六項
[1] 52.86879 50.79304 49.25390 41.76034 44.41400 49.13812
> summary(a)
Min. 1st Qu. Median Mean 3rd Qu. Max.
38.77 46.33 49.00 49.29 52.24 61.16
> fix(a)
29.
vectors(2)
> b =c(1,2,3,4,5,6) #### 使用 c() 建立 vector,包含數字項
> str(b)
num [1:6] 1 2 3 4 5 6
> c = c(“1”,“2”,“3”,“4”,“5”,“6”) #### 使用 c() 建立 vector,由字串構成
> str(c)
chr [1:6] "1" "2" "3" "4" "5" "6"
> summary(b)
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 2.25 3.50 3.50 4.75 6.00
> summary(c)
Length Class Mode
6 character character
30.
vectors(3)
> mean(b)
[1] 3.5
>mean(c)
[1] NA
警告訊息:
In mean.default(c) : argument is not numeric or logical: returning NA
> d = as.numeric(c) ### help(as)
> str(d)
num [1:6] 1 2 3 4 5 6
> mean(d)
[1] 3.5
useful commands onvectors
sample(x, 4) # randomly picks four states
sample(x) # randomly permute the entire vector
of state names
sample(x, replace=TRUE) # selection with
replacement
33.
useful commands onvectors
rev(x) # reverses the vector
sum(x) # sums all the elements in a numeric or logical vector
cumsum(x) # returns a vector of cumulative sums (or a
running total)
diff(x) # returns a vector of differences between adjacent
elements
max(x) # returns the largest element
min(x) # returns the smallest element
range(x) # returns a vector of the smallest and largest
elements
mean(x) # returns the arithmetic mean
list()
• Lists canhold data structures of different
types, and of different sizes.
• Each component in a list can be (optionally,
but commonly) separately named.
43.
list()
• A listof Peter O’Toole
pete <- list("Peter", "O'Toole", 1932, FALSE)
print(pete)
pete <- list(first.name = "Peter", last.name =
"O'Toole", yob = 1932, oscar.winner = FALSE)
print(pete)
44.
list()
m1 <- list(title= "Lawrence of Arabia", year = 1962)
m2 <- list(title = "Stardust", year = 2007)
m3 <- list(title = "Troy", year = 2004)
pete$movies <- list(m1, m2, m3)
pete[["roles"]] <- c("T.E. Lawrence", "King", "Priam")
str(pete)
45.
Data frame
• Dataframes are two-dimensional data
structures like matrices, but unlike matrices
can have multiple different data types.
• You can think of a data frame as a list of
vectors, where all the vector lengths are the
same.