[R基础] 数据形式:向量、函数、变量、数组、数据框、列表、类和对象和模型与公式

ctrl +L 清空console界面

1. 向量

> 2*9+3
[1] 21
> c(1,5,4,78,3)  #c必须是小写
[1]  1  5  4 78  3
> length(x)    #元素个数
[1] 5
> mode(x)
[1] "numeric"
> c('hello','world')  #单引号
[1] "hello" "world"
> c("hello","world")  #双引号,一样的结果
[1] "hello" "world"  

> c(1,2,3,4)+c(4,5,6,7)
[1]  5  7  9 11
> c(1,2,3,4)+c(1,2)
[1] 2 4 4 6
> 1:6
[1] 1 2 3 4 5 6
> c(1,2,3,4)>c(4,1,6,2)
[1] FALSE  TRUE FALSE  TRUE

2. 函数

> exp(1)
[1] 2.718282
> exp(1:4)
[1]  2.718282  7.389056 20.085537 54.598150

3. 变量

> x<-c(5:10)
> x
[1]  5  6  7  8  9 10
> x[3]      #从变量x中取出某一个元素的话,可以使用方括号加索引号
[1] 7
> x[3:5]    #选择第三到第五位置的数
[1] 7 8 9
> x[-3]     #删除第3个数
[1]  5  6  8  9 10
> x[x>8]    #x>8是表达式
[1]  9 10

4. 数组

> a<-array(2:13, c(3,4))  #三行四列的数组,默认按竖排
> a
     [,1] [,2] [,3] [,4]
[1,]    2    5    8   11
[2,]    3    6    9   12
[3,]    4    7   10   13
> a[3,3]
[1] 10
> a[2, ]                 #第二行的数
[1]  3  6  9 12
> a[ ,2]                 #第二列的数
[1] 5 6 7

5. 数据框

每列的数据类型可以不同,但数据长度必需一致。

> city<-c('a','b','c','c')
> age<-c(12,23,25,45)
> id<-c(12,14,13,16)
> df<-data.frame(id,city,age)    #变量组合成数据框
> df
  id city age
1 12    a  12
2 14    b  23
3 13    c  25
4 16    c  45
> df$age                        #取age列
[1] 12 23 25 45
> df[ ,3]
[1] 12 23 25 45
> df['age']
  age
1  12
2  23
3  25
4  45
> df$age>20
[1] FALSE  TRUE  TRUE  TRUE
> df[df$age>20, ]              #选择age>20的行
  id city age
2 14    b  23
3 13    c  25
4 16    c  45

6. 列表

列表(List)是最为灵活的数据结构,它的不同元素可以是不同类型。

> people<-list(id=id, city=city, age=age)
> people
$id
[1] 12 14 13 16

$city
[1] "a" "b" "c" "c"

$age
[1] 12 23 25 45

> people$df2<-df          #数据框df作为list的一个元素
> people
$id
[1] 12 14 13 16

$city
[1] "a" "b" "c" "c"

$age
[1] 12 23 25 45

$df2
  id city age
1 12    a  12
2 14    b  23
3 13    c  25
4 16    c  45

7. 类与对象

对于任何一个对象,我们可以用class()函数来观察它的类。

> class(people)
[1] "list"
> class(df)
[1] "data.frame"
> class(city)
[1] "character"
> class(age)
[1] "numeric"

8. 模型与公式

> head(cars) //内置的数据集cars  //head函数提取数据的前6行数
  speed dist
1     4    2
2     4   10
3     7    4
4     7   22
5     8   16
6     9   10
> model<-lm(formula = dist~speed,data=cars)   #lm线性函数
> class(model)
[1] "lm"

> attributes(model)      #model的属性
$names
 [1] "coefficients"  "residuals"     "effects"      
 [4] "rank"          "fitted.values" "assign"       
 [7] "qr"            "df.residual"   "xlevels"      
[10] "call"          "terms"         "model"        

$class
[1] "lm"

> model$coefficients     #调用coefficients
(Intercept)       speed 
 -17.579095    3.932409 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值