{R语言学习日记}Day4 hello world
大家好,我是William李梓峰,欢迎阅读我的 R 语言学习日记。
官网链接:
https://www.tutorialspoint.com/r/r_basic_syntax.htm
As a convention, we will start learning R programming by writing a "Hello, World!" program. Depending on the needs, you can program either at R command prompt or you can use an R script file to write your program. Let's check both one by one.
按照惯例,我们先来写个 R 语言的 "Hello, World!" 程序。你可以根据喜好来决定到底是直接使用 R 命令行窗口还是 R 脚本文件。不过,我们两者都会介绍。
R Command Prompt
R 命令行窗口
Once you have R environment setup, then it’s easy to start your R command prompt by just typing the following command at your command prompt −
一旦你已经安装了 R 语言环境,就可以非常轻易地启动你的 R 命令行窗口了,只需在命令行那里敲下 R:
$ R
This will launch R interpreter and you will get a prompt > where you can start typing your program as follows −
敲下 R 以后会立即启动 R 解释器,然后你就可以在 > 后面输入 R 代码了:
> myString <- "Hello, World!"
> print ( myString)
[1] "Hello, World!"
Here first statement defines a string variable myString, where we assign a string "Hello, World!" and then next statement print() is being used to print the value stored in variable myString.
上面的代码中,第一行表示定义了一个字符串变量 myString,并且给它赋值了字符串 “Hello, World!”,然后在第二行代码中打印它。
R Script File
R 脚本文件
Usually, you will do your programming by writing your programs in script files and then you execute those scripts at your command prompt with the help of R interpreter called Rscript. So let's start with writing following code in a text file called test.R as under −
通常来说,你会直接在脚本文件中编程,然后你会通过一个叫 Rscript 的 R 解释器在命令行窗口中执行这些脚本。接下来,让我们开始在一个名为 test.R 的文件中编写 R 代码吧:
# My first program in R Programming
myString <- "Hello, World!"
print ( myString)
Save the above code in a file test.R and execute it at Linux command prompt as given below. Even if you are using Windows or other system, syntax will remain same.
保存上面的代码,然后执行这个文件。即便你在 Windows 或其他系统,命令都是一样的:
$ Rscript test.R
When we run the above program, it produces the following result.
当我们运行上面的程序的时候,它就给出了下面的结果:
[1] "Hello, World!"
Comments
R 语言的注释
Comments are like helping text in your R program and they are ignored by the interpreter while executing your actual program. Single comment is written using # in the beginning of the statement as follows −
注释就像是一个提示文本,它们总会被解释器所忽略掉。单行注释可以用 # 来表示:
# My first program in R Programming
R does not support multi-line comments but you can perform a trick which is something as follows −
R 语言不支持多行注释,但是你可以像下面这么操作来达到多行注释的效果:
if(FALSE) {
"This is a demo for multi-line comments and it should be put inside either a single
OR double quote"
}
myString <- "Hello, World!"
print ( myString)
Though above comments will be executed by R interpreter, they will not interfere with your actual program. You should put such comments inside, either single or double quote.
虽然上面的注释会被 R 解释器执行,但它们不会影响你程序的逻辑。你可以随便扔些文本进去,用单引号双引号都行。