R语言入门学习--数据类型

本文介绍了R语言中的基本数据结构,包括向量、列表、矩阵、数组、因子和数据框等,并通过实例演示了如何创建这些数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值