R語言Data Frame常用用法


Data Frame是R中最常用的數據結構,由行和列組成,相當於R中的表,與Matrix每列數據類型必須相同的區別是,數據框每個列可以是不同的數據類型。

Data Frame每一列有列名,每一行也可以指定行名。如果不指定行名,那么就是從1開始自增的Sequence來標識每一行。

(1) 創建數據框

> patientID <- c(1:4)
> age <- c(25,31,42,57)
> diabetes <- c("Type1","Type2","Type3","Type4")
> status <- c("Poor","Improved","Excellent","Poor")
> patientdata <- data.frame(patientID,age,diabetes,status)
> patientdata
patientID age diabetes status
1 1 25 Type1 Poor
2 2 31 Type2 Improved
3 3 42 Type3 Excellent
4 4 57 Type4 Poor

(2)與Matrix一樣,使用[行Index,列Index]的格式可以訪問具體的元素。

> patientdata
patientID age diabetes status
1 1 25 Type1 Poor
2 2 31 Type2 Improved
3 3 42 Type3 Excellent
4 4 57 Type4 Poor
> patientdata[1,]
patientID age diabetes status
1 1 25 Type1 Poor
> patientdata[,1]
[1] 1 2 3 4
> patientdata[1]
patientID
1 1
2 2
3 3
4 4

patientdata[1:2]
patientdata[c("patientID","age")]

patientID age
1 1 25
2 2 31
3 3 42
4 4 57

(3) attach()、 detach()和with()    使用attach和detach函數可以使得訪問列時不需要總是跟着變量名在前面。

比如要打印所有age,那么可以寫成:

> print(age)
[1] 25 31 42 57
> detach(patientdata)

with實現相同的功能

> with(patientdata,{
+ print(age)
+ })
[1] 25 31 42 57

(4) 查看數據類型

> str(patientdata)
'data.frame': 4 obs. of 4 variables:
$ patientID: int 1 2 3 4
$ age : num 25 31 42 57
$ diabetes : Factor w/ 4 levels "Type1","Type2",..: 1 2 3 4
$ status : Factor w/ 3 levels "Excellent","Improved",..: 3 2 1 3

修改數據類型

patientdata$diabetes<-as.character(patientdata$diabetes)

(5) 增加列:> patientdata$name <- c("Bob","Allen","Tom","Jack")

(6) 查詢/子集

查詢一個Date Frame,返回一個滿足條件的子集,這相當於數據庫中的表查詢,是非常常見的操作。使用行和列的Index來獲取子集是最簡單的方法,前面已經提到過。如果我們使用布爾向量,配合which函數,可以實現對行的過濾。

這里我們想得到status為Poor的人的情況:

> patientdata[which(patientdata$status=="Poor"),]
patientID age diabetes status name
1 1 25 Type1 Poor Bob
4 4 57 Type4 Poor Jack

如果只想知道status為Poor的人的姓名:

> patientdata[which(patientdata$status=="Poor"),"name"]
[1] "Bob" "Jack"

還可以用subset更為簡潔:

> subset(patientdata,status=="Poor" & age < 30,select = c("name","diabetes"))
name diabetes
1 Bob Type1

還可以用sql語句:

> library(sqldf)
> result<-sqldf("select * from patientdata where status='Poor' and age<30")
> result
patientID age diabetes status name
1 1 25 Type1 Poor Bob

(7)數據框連接

> patientdata1 <- patientdata
> rbind(patientdata,patientdata1)   ##按照列連接,列數必須相同
patientID age diabetes status name
1 1 25 Type1 Poor Bob
2 2 31 Type2 Improved Allen
3 3 42 Type3 Excellent Tom
4 4 57 Type4 Poor Jack
5 1 25 Type1 Poor Bob
6 2 31 Type2 Improved Allen
7 3 42 Type3 Excellent Tom
8 4 57 Type4 Poor Jack
> cbind(patientdata,patientdata1)   ##按照行連接,行數必須相同
patientID age diabetes status name patientID age diabetes status name
1 1 25 Type1 Poor Bob 1 25 Type1 Poor Bob
2 2 31 Type2 Improved Allen 2 31 Type2 Improved Allen
3 3 42 Type3 Excellent Tom 3 42 Type3 Excellent Tom
4 4 57 Type4 Poor Jack 4 57 Type4 Poor Jack

 (8) 更改數據框所有數據的格式

 df<- lapply(df,as.numeric)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM