在R语言中编写程序的两种方法
1. 命令提示符--R语言解释器
2. 脚本文件(这个不会)
在脚本文件中编写程序,然后再R语言解释器中调用Rscrit执行脚本文件
R语言的数据类型
不像其他语言,需要指定变量的数据类型。R的数据类型都是有R的对象来指定的,最基础的有向量,同一个向量里的变量必须是同一种类型。然后还有list(一维的多个向量),矩阵,数组,数据框。
----向量
> #creat a ventor
> apple<- c("red","green","yellow")
> print(apple)
[1] "red" "green" "yellow"
> print(class(apple))
[1] "character"
>
----列表
> #creat a list
> studentdata<- list(c("Jack","Rose"),18,19,sin,"sin")
> print(studentdata)
[[1]]
[1] "Jack" "Rose"
[[2]]
[1] 18
[[3]]
[1] 19
[[4]]
function (x) .Primitive("sin")
[[5]]
[1] "sin"
> print(class(studentdata))
[1] "list"
>
-----矩阵 matrix(根据数据个数合理分配行数和列数)
> studentname<- matrix(c("Jack","Rose","Mary","Jane","Mike"),nrow=2,ncol=3,byrow=TRUE)
Warning message:
In matrix(c("Jack", "Rose", "Mary", "Jane", "Mike"), nrow = 2, ncol = 3, :
数据长度[5]不是矩阵行数[2]的整倍
> studentname<- matrix(c("Jack","Rose","Mary","Jane","Mike","Marthew"),nrow=2,ncol=3,byrow=TRUE)
> print(studentname)
[,1] [,2] [,3]
[1,] "Jack" "Rose" "Mary"
[2,] "Jane" "Mike" "Marthew"
----数组array,默认是按照列填充,没有byrow参数
> id<- array(c(1,2,3,4,5,6),dim=c(3,3,2))
> print(id)
, , 1
[,1] [,2] [,3]
[1,] 1 4 1
[2,] 2 5 2
[3,] 3 6 3
, , 2
[,1] [,2] [,3]
[1,] 4 1 4
[2,] 5 2 5
[3,] 6 3 6
> id<- array(c(1,2,3,4,5,6),dim=c(3,3,2),byrow=TRUE)
Error in array(c(1, 2, 3, 4, 5, 6), dim = c(3, 3, 2), byrow = TRUE) :
参数没有用(byrow = TRUE)
---因子factor
因子是由向量组成的,它会将向量中的不管是字符还是数字,布尔都储存成标签。在输出因子时,会相应的输出对应向量中有哪些标签。
+ > apple_colors<- c("green","red","red","red","yellow","green")
> factor_apple<- factor(apple_colors)
> print(factor_colors)
Error in print(factor_colors) : 找不到对象'factor_colors'
> print(factor_apple)
[1] green red red red yellow green
Levels: green red yellow
> apple_colors<- c(1,2,1,3,6,5,3)
> factor_apple<- factor(apple_colors)
> print(factor_apple)
[1] 1 2 1 3 6 5 3
Levels: 1 2 3 5 6
>
---数据框frame
数据框可以将不同类型的向量放在一起由此构成表结构
> )> > )> BMI<- data.frame(
+ name=c("Jack","Rose","Mike"),
+ age=c(17,16,18),
+ height=c(175.5,163,184)
+ )
> print(BMI)
name age height
1 Jack 17 175.5
2 Rose 16 163.0
3 Mike 18 184.0
> name=c("jack","rose","mike"),
错误: 意外的',' in "name=c("jack","rose","mike"),"
> name=c("jack","rose","mike")
> name<- c("jack","rose","mike")
> age<- c(17,16,19)
> height<- c(176,163,184)
> BMI<- data.frame(name,age,height)
> print(BMI)
name age height
1 jack 17 176
2 rose 16 163
3 mike 19 184
>