R语言边学边记--数据结构

阿三

矩阵:

> n1<-c("a","b","c","d")

> n2<-c("A","B","C")

> p<-matrix(1:12,nrow = 4,ncol = 3,byrow = T,dimnames = list(n1,n2))

> p

   A  B  C

a  1  2  3

b  4  5  6

c  7  8  9

d 10 11 12

> p[1,2]

[1] 2

> p[2]

[1] 4

> p[5]

[1] 2

> p[3,4]

Error in p[3, 4] : subscript out of bounds

> p[2,c(2,3)]

B C 

5 6 

> p[3,]

A B C 

7 8 9 

> p[,3]

 a  b  c  d 

 3  6  9 12 

3.数组

> e<-c("A","B","C","D")

> b<-array(1:16,c(2,2,4),dimnames = list(q,w,e))

> q<-c("a","b")

> w<-c("武大郎","武二郎")

> e<-c("A","B","C","D")

> b<-array(1:16,c(2,2,4),dimnames = list(q,w,e))

> b

, , A


  武大郎 武二郎

a      1      3

b      2      4


, , B


  武大郎 武二郎

a      5      7

b      6      8


, , C


  武大郎 武二郎

a      9     11

b     10     12


, , D


  武大郎 武二郎

a     13     15

b     14     16


> b[2,2,1]

[1] 4

> b[1,2,4]

[1] 15

数据框


数据框生成

> age<-c(22,2,33,24)

> gender<-c("male","female","male","female")

> grade<-c(88,2,2,23)

> df1<-data.frame(age,gender,grade)

> df1

  age gender grade

1  22   male    88

2   2 female     2

3  33   male     2

4  24 female    23

> df1[1]

  age

1  22

2   2

3  33

4  24

> df1[4,1]

[1] 24

> df1[,3]

[1] 88  2  2 23

> df1[1:3,]

  age gender grade

1  22   male    88

2   2 female     2

3  33   male     2

> df1[1:3,3]

[1] 88  2  2

> df1[-1,]

  age gender grade

2   2 female     2

3  33   male     2

4  24 female    23

> df1["age"]

  age

1  22

2   2

3  33

4  24

> df1[c()]

data frame with 0 columns and 4 rows

> df1$gender

[1] male   female male   female


> a<-c(2,3,1,4,5)

> b<-matrix(1:20,nrow = 4,ncol = 5)

> age<-c(1,5)

> country<-c("Chian","India")

> c<-data.frame(age,country)

> list1<-list(a=a,b=b,c=c)

> list1[1][3]

$

NULL


> list1[3][age]

$c

  age country

1   1   Chian

2   5   India


$

NULL


> list1[[1]][4]

[1] 4

> list1[[3]][2][1]

  country

1   Chian

2   India

> list1[[[3]]][[2]][1]

Error: unexpected '[' in "list1[[["

> list1[[3]][2,1]

[1] 5

> list1$a

[1] 2 3 1 4 5

> list1$c

  age country

1   1   Chian

2   5   India

总结


你可能感兴趣的:(R语言边学边记--数据结构)