本篇文章由 VeriMake 旧版论坛中备份出的原帖的 Markdown 源码生成
原帖标题为:R 语言 | 基础语法
原帖网址为:https://verimake.com/topics/217 (旧版论坛网址,已失效)
原帖作者为:dawdler(旧版论坛 id = 64,注册于 2020-08-17 14:01:22)
原帖由作者初次发表于 2021-05-25 18:36:38,最后编辑于 2021-05-25 18:36:38(编辑时间可能不准确)
截至 2021-12-18 14:27:30 备份数据库时,原帖已获得 345 次浏览、0 个点赞、0 条回复
R语言
1. 基础语法
1.1
按照惯例,学习一门新的语言学习一般都是从输出 "Hello, world!" 开始的——
#my first program
myStr <- "Hello, world!"
print (myStr)
以上实例将字符串"Hello, world!"赋值给myStr
变量,并通过print()
函数输出。
![](https://verimake.com/assets/files/2022-01-26/1643184531-203234-40.png)
注意:R语言赋值使用左箭头<-
符号赋值,但现在的新版本也支持等号=
进行左赋值。
1.2 变量命名
R语言支持由字母、数字以及点号.
或下划线_
组成的变量名,并且要以字母或点号.
开头。
![](https://verimake.com/assets/files/2022-01-26/1643184555-58225-41.png)
1.3 打印输出
print()
和cat()
是R语言的两个最基本的输出函数,其中print()
可以直接输出单个数字、字符等,cat()
常用于输出拼接的结果——
#print
print("verimake")
print("123")
print(3e2)
#concatenate
cat(1,"+",1,"=",2,'\n')
![](https://verimake.com/assets/files/2022-01-26/1643184593-911547-42.png)
其中,cat()
会在每两个拼接元素之间自动加上空格。
1.4 注释
在一般的编程语言中,注释可以被分为单行注释和多行注释,但到目前为止,R语言仅支持单行注释,注释符号为#
。
#单行注释
myStr <- "hello world"
print (myStr)
如果想要进行多行注释,我们可以在每一行行首添加#
或者借助一个条件为假的判断语句来实现——
#多行注释
if(FALSE){
"
在这里
进行
多行注释
"
}
1.5 列出和删除
1.5.1 工作目录
我们可以通过getwd()
来获取当前工作的目录,也可以通过setwd()
来设置当前工作的目录——
#get and print current working directory
print(getwd())
#set current working directory
setwd("C:/Users/caiya")
print(getwd())
输出结果:
![](https://verimake.com/assets/files/2022-01-26/1643184667-557136-43.png)
1.5.2 查看变量
如果想查看工作空间中当前可用的变量,我们可以借助ls()
函数,并且可以使用rm()
函数进行删除。
myStr <- "hello world"
tax = 0.13
price = 98
#listing
print(ls())
#removing
rm(tax)
print(tax)
print(ls())
可以看到,在rm(tax)
操作后,tax已经查无此变量了——
![](https://verimake.com/assets/files/2022-01-26/1643184701-965232-44.png)
同时,我们可以通过使用ls()
和rm()
删除所有变量:
#rm() and ls()
rm(list = ls())
print(ls())
并产生character(0)
的运行结果。
下一期就要讲基本的数据类型啦!
相关资料:
https://www.runoob.com/r/r-basic-syntax.html
https://www.runoob.com/r/r-comments.html