1. 程式人生 > >R語言實戰-數據類型-2(數據框dataframe)

R語言實戰-數據類型-2(數據框dataframe)

ram win fault erro frame rem 同時 default 個數

5、數據框dataframe data.frame

創建

data.frame()

 1 > a<-c(1,2,3,4,5)
 2 > b<-c(a,b,c,d,e)
 3 > c<-c(T,F,F,F,T)
 4 > x<-data.frame(a,b,c)
 5 > x
 6   a b     c
 7 1 1 a  TRUE
 8 2 2 b FALSE
 9 3 3 c FALSE
10 4 4 d FALSE
11 5 5 e  TRUE

PS:子元素個數不同時會報錯

1 > a<-c(1,2,3,4,5,6,7)
2 > b<-c(a,b,c,d,e)
3 > c<-c(T,F,F,F,T)
4 > x<-data.frame(a,b,c)
5 Error in data.frame(a, b, c) : 參數值意味著不同的行數: 7, 5

PS:dataframe與其他語言中的dataset數據集類似

數據引用

 1 > x[c(a,c)]
 2   a     c
 3 1 1  TRUE
 4 2 2 FALSE
 5 3 3 FALSE
6 4 4 FALSE 7 5 5 TRUE 8 > x[2:3] 9 b c 10 1 a TRUE 11 2 b FALSE 12 3 c FALSE 13 4 d FALSE 14 5 e TRUE 15 > x[2:3,2] 16 [1] b c 17 Levels: a b c d e 18 > x[2:3,1] 19 [1] 2 3 20 > x[2:3,3] 21 [1] FALSE FALSE

PS:$引用法

1 > x$a
2 [1] 1 2 3 4 5

attach()與detach()

 1 > attach(x)
 2 The following objects are masked _by_ .GlobalEnv:
 3 
 4     a, b, c
 5 
 6 > a
 7 [1] 1 2 3 4 5 6 7
 8 > b
 9 [1] "a" "b" "c" "d" "e"
10 > c
11 [1]  TRUE FALSE FALSE FALSE  TRUE
12 > a[5]
13 [1] 5
14 > b[3]
15 [1] "c"
16 > detach(x)
17 > a
18 [1] 1 2 3 4 5 6 7
19 > b
20 [1] "a" "b" "c" "d" "e"
21 > c
22 [1]  TRUE FALSE FALSE FALSE  TRUE
23 > remove(a,b)
24 > remove(c)
25 > a
26 Error: object a not found
27 > b
28 Error: object b not found
29 > attach(x)
30 > a
31 [1] 1 2 3 4 5
32 > b
33 [1] a b c d e
34 Levels: a b c d e
35 > detach(x)

with()

1 > with(x,{
2 +   m<-a[1]+a[5]
3 +   m
4 +   n<-paste(b[1],b[2],b[5],sep = +)
5 +   n
6 + })
7 [1] "a+b+e"

Usage

data.frame(..., row.names = NULL, check.rows = FALSE,
           check.names = TRUE, fix.empty.names = TRUE,
           stringsAsFactors = default.stringsAsFactors())

R語言實戰-數據類型-2(數據框dataframe)