一.R語言向量(vector)及標量(scale)
1.向量:將向量拆分成“向”和“量”二字捌治,前者表示方向,后者表示變量肖油,再合二為一,即具有方向的變量森枪。
2.標量:也就是沒有方向的變量视搏,在更多的情況下县袱,我們接觸的都是標量。
x1 <- c(2,-2)
x2 <- c(-2,2)
identical(x1,x2)
[1] FALSE
my_vec <- c(1:10)
my_vec
[1] 1 2 3 4 5 6 7 8 9 10
my_scale<-()
二.數(shù)據(jù)框(data.frame)
Data Frame一般被翻譯為數(shù)據(jù)框式散,感覺就像是R中的表,由行和列組成漓滔,與Matrix不同的是,每個列可以是不同的數(shù)據(jù)類型响驴,而Matrix是必須相同的。
my_df <- data.frame(num = 1:5, letter = LETTERS[1:5], logic = c(T,F,T,F,T))
my_df
num letter logic
1 1 A TRUE
2 2 B FALSE
3 3 C TRUE
4 4 D FALSE
5 5 E TRUE
my_df2 <- data.frame(1:5, LETTERS[1:5])
my_df2
X1.5 LETTERS.1.5.
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
my_df3 <- data.frame(num = 1:5, letter = LETTERS[1:5], logic = c(T,F,T,F,T), row.names = paste('row',1:5))
my_df3
num letter logic
row 1 1 A TRUE
row 2 2 B FALSE
row 3 3 C TRUE
row 4 4 D FALSE
row 5 5 E TRUE
數(shù)據(jù)框的讀取
read.table函數(shù) 了解read.table各個參數(shù)的意義踏施。
??read.table
read.table(file, header = FALSE, sep = "", quote = "\"'",
dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"),
row.names, col.names, as.is = !stringsAsFactors,
na.strings = "NA", colClasses = NA, nrows = -1,
skip = 0, check.names = TRUE, fill = !blank.lines.skip,
strip.white = FALSE, blank.lines.skip = TRUE,
comment.char = "#",
allowEscapes = FALSE, flush = FALSE,
stringsAsFactors = default.stringsAsFactors(),
fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)
三.實例操作
讀取實例數(shù)據(jù)
> getwd()#顯示工作路徑
[1] "H:/Figure"
> setwd("H:/Figure")#設(shè)置工作路徑
> a<-read.table(file = "huahua.txt",sep = "\t",header =T) #讀取文件罕邀,分隔符為Tab,有表頭
> dim(a)
[1] 5 2
> is.data.frame(a)
[1] TRUE
> summary(a)
X1 X2
A:1 Min. :1.0
B:1 1st Qu.:1.5
C:1 Median :2.0
D:1 Mean :2.0
E:1 3rd Qu.:2.5
Max. :3.0
NA's :3
>
> b<-read.table(file = "doudou.txt",sep = ",",header =T)#分隔符從\t變?yōu)?
> x<-read.csv('doudou.txt')
> rownames(x)#查看行名
[1] "1" "2" "3" "4" "5"
> colnames(x)#查看列名
[1] "X1" "X2"
> colnames(x)<-c("age",'names')
> x
age names
1 A 1
2 B NA
3 C NA
4 D 3
5 E NA
Attach及With函數(shù)
attach(what, pos = 2L, name = deparse(substitute(what)),
warn.conflicts = TRUE)
with(data, expr, ...)
小括號是函數(shù)的代表诉探,一個函數(shù)之所以能成為一個函數(shù),那是因為它的名稱后面跟了一個小括號肾胯;中括號是提取子集用的耘纱,用途十分廣泛;R語言中毕荐,大括號{}主要在條件語句和循環(huán)語句中出現(xiàn).
> c <-data.frame(case=paste("S",c(1:50)),values=runif(50))
> head(c)
case values
1 S 1 0.4543641
2 S 2 0.5379318
3 S 3 0.3096288
4 S 4 0.6699199
5 S 5 0.2579748
6 S 6 0.6403503
> plot(c$case,c$values)
> attach(c)
The following objects are masked from c (pos = 3):
case, values
> plot(case,values)
>
> with(c,{
+ plot(case,values)
+ x<<-summary(values) #求和并賦值給x,<<的意思是作為全局變量,y也就是出了with循環(huán)仍有效憎亚。
+ })
> x
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.05874 0.33941 0.60480 0.57536 0.81688 0.98565