5種基本類型的對(duì)象
字符character
雙引號(hào)或單引號(hào)夾起來晒夹,如“字符”
賦值 orange 為字符串 red梅割、green、yellow蹦掐,顯示字符串技羔,查看字符串?dāng)?shù)據(jù)類型,計(jì)算字符串長(zhǎng)度卧抗。
# Create a vector
orange <- c('red','green',"yellow")
print(orange)
[1] "red" "green" "yellow"
# Get the class of the vector
print(class(orange))
[1] "character"
length(orange)
[1] 3
證書integer
復(fù)數(shù)complex
如x+ab
邏輯logical
true/false
邏輯假和真的幾種形式藤滥,查看邏輯假的變量類型。
# 假
F / FALSE / 0
F
[1] FALSE
# 真
T / TRUE / !0
class(T)
[1] "logical"
數(shù)值numeric
整數(shù)社裆、小數(shù)拙绊、科學(xué)計(jì)數(shù)的方式,默認(rèn)雙精度型數(shù)據(jù)泳秀,real numbers
6種儲(chǔ)存數(shù)據(jù)的對(duì)象類型:
因子factor
分類型數(shù)據(jù)需要把數(shù)據(jù)分為不同的水平标沪,如性別分為男女兩個(gè)因子
向量vector
有相同基本類型元素組成的序列,相當(dāng)于一維數(shù)組
賦值變量 x 為 1,2,3 / 1,2,3,4,5,6,7,8,9; 取值 2,3 / 3 / 3,2,1; 輸出字符串和變量(myString) Hello World晶默; 輸出 3.9 與 1.6 之和谨娜。
x<-c(1,2,4) / x<-c(1:9) / x[c(0,0,1)]
x
[1] 1 2 4
c(1,2,4)->x
x
[1] 1 2 4
x[2:3] / x[3] / x[c(3,2,1)]
[1] 2 4
print("Hello World")
[1] Hello World
# Add two numbers
print(3.9 + 1.6)
[1] 5.5
myString <- "Hello, World!"
print ( myString) / cat(myString,"\n")
[1] "Hello, World!"
賦值隱藏變量 a 為 2,3,4,var_123 為 123磺陡;顯示所有變量 趴梢、隱藏變量;正則 var*币他;刪除 隱藏變量 a坞靶;顯示所有變量。
.a<-c(2,3,4)
var_123=123
ls()
[1] "a" "var_123"
ls(all.name=TRUE)
[1] ".a" "a" "var_123"
ls(pattern="var")
[1] "var_123"
rm(.a)/remove(.a)
ls(all.name=T)
[1] "a" "d" "var_123"
矩陣matrix
以 1,2,4,8(cells蝴悉、rnames彰阴、cnames) 構(gòu)建矩陣 mymatrix
C1 C2
R1 1 2
R2 4 8
cells<- c(1,2,4,8)
rnames<-c("R1", "R2")
cnames<-c("C1", "C2")
mymatrix<-matrix(cells, nrow=2, ncol=2, byrow=TRUE, dimnames=list(rnames, cnames))
mymatrix
# C1 C2
# R1 1 2
# R2 4 8
列表list
向量、矩陣和數(shù)組的元素必須是同一類型的數(shù)據(jù)拍冠,但是如果一個(gè)數(shù)據(jù)對(duì)象需要含有不同的數(shù)據(jù)類型尿这,則采用列表
g(title) 為 My First List, h(ages) 為 25, 26, 18, 39, j 為 1~10(5行)的矩陣,k 為字符串 one, two, three 建數(shù)據(jù)列表 mylist庆杜;
g<-"My First List"
h<-c(25, 26, 18, 39)
j<-matrix(1:10, nrow=5)
k<-c("one", "two", "three")
mylist<-list(title=g, ages=h, j, k)
mylist
$title
[1] "My First List"
$ages
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] "one" "two" "three"
數(shù)組array
一維數(shù)組是向量射众,二維數(shù)組是矩陣。向量和矩陣的推廣
數(shù)據(jù)框data.frame
一種矩陣形式的數(shù)據(jù)晃财,可以是不同類型的數(shù)據(jù)叨橱。
patientID 為 1, 2, 3, 4,age 為 25, 34, 28, 52, diabetes 為 Type1, Type2, Type1, Type1,status 為 Poor, Improved, Excellent, Poor 建數(shù)據(jù)框 patientdata罗洗。
# method 2
patientID <- c(1, 2, 3, 4)
age <- c(25, 34, 28, 52)
diabetes <- c("Type1", "Type2", "Type1", "Type1")
status <- c("Poor", "Improved", "Excellent", "Poor")
patientdata <- data.frame(patientID, age, diabetes, status)
head(patientdata)
# patientID age diabetes status
#1 1 25 Type1 Poor
#2 2 34 Type2 Improved
#3 3 28 Type1 Excellent
#4 4 52 Type1 Poor