R Language Fundamentals
Learning a new language usually starts with a program that outputs "Hello, World!"; the R "Hello, World!" program is as follows:
Example (helloworld.R)
myString
<-
"Hello, World!"
(
myString
)
Run Example »
The above example assigns the string "Hello, World!" to the variable myString, then outputs it using the print() function.
Note:R assignment uses the left arrow <- symbol, although some newer versions also support the equal =。
Note:The most common script file extension in R is .R。
For example:
hello.R
data_analysis.R stock.R
Although .r also works, but the community overwhelmingly uses .R。
Variables
Valid variable names in R consist of letters, digits, and the dot . or underscore _.
A variable name begins with a letter or a dot.
| Variable Name | Is it correct | Reason |
|---|---|---|
| var_name2. | Correct | Starts with a character and consists of letters, digits, underscores, and dots |
| var_name% | Error | % is an illegal character |
| 2var_name | Error | Cannot start with a digit |
|
.var_name, var.name |
Correct | Can start with a dot, but note that a leading dot cannot be followed by a digit |
| .2var_name | Error | A leading dot cannot be followed by a digit |
| _var_name | Error | Cannot start with an underscore _ |
Variable assignment
The latest version of R supports assignment with the left arrow <-, equal sign =, and right arrow ->:
Example
Assign using the equal sign =
var.1
=
c
(
0
,
1
,
2
,
3
)
(
var.1
)
[
1
]
0
1
2
3
Assign using the left arrow <-
var.2
<-
c
(
"learn"
,
"R"
)
(
var.2
)
[
1
]
"learn"
"R"
Assign using the right arrow ->
c
(
TRUE,
1
)
->
var.3
(
var.3
)
[
1
]
1
1
To view defined variables, you can use ls() functions as follows:
Example
(
ls
(
)
)
[
1
]
"var.1"
"var.2"
"var.3"
To delete variables, you can use rm() functions as follows:
Example
rm
(
var.3
)
(
ls
(
)
)
[
1
]
"var.1"
"var.2"
In the previous chapter, we learned how to install the R programming environment; next we introduce interactive programming and file script programming in R.
Interactive programming
We only need to run the R command at the command line to enter the interactive programming window:
R
After running this command, the R interpreter is launched, and we can enter code after the > prompt.

You can exit the interactive session by entering q():
> q()
Save workspace image? [y/n/c]: y

File scripts
R language files use the .R extension.
Next, we create a runoob-test.R file with the following code:
The runoob-test.R file
myString
<-
"RUNOOB"
(
myString
)
Next, we use Rscript in the command-line window to execute the script:
Rscript runoob-test.R
The output is as follows:
[1] "RUNOOB"

Input/Output
print() output
print() is the output function in R.
Like other programming languages, R supports output of numbers, characters, and more.
The output statement is very simple:
print("RUNOOB")
print(123)
print(3e2)
Execution result:
[1] "RUNOOB"
[1] 123
[1] 300
Like node.js and Python, R is an interpreted language, so we can often use R like a command line.
If we enter a value on a line, R will output it directly in normalized form:
> 5e-2
[1] 0.05
Why does R's printed output include [1]?
Many beginners, seeing this for the first time:
[1] 30
do not know what it means; this [1] is not an array index.
[1] means this line of output starts from the first element.
Because R is inherently a vectorized language.
For example:
x <- c(10,20,30)
print(x)
Output:
[1] 10 20 30
If the content is too long:
[1] ...
[4] ...
[7] ...
it indicates which element this line starts from.
The cat() function
If you need to concatenate output results, you can use the cat() function:
Example
cat
(
1
,
"plus"
,
1
,
"equals"
,
2
,
'\n'
)
1
Addition
1
Equal
2
The cat() function automatically adds a space between each pair of concatenated elements.
Writing output to a file
R offers many convenient ways to write output to a file.
The cat() function supports writing output directly to a file:
cat("RUNOOB", file="/Users/runoob/runoob-test/r_test.txt")
This statement produces no console output; instead it writes "RUNOOB" to the file "/Users/runoob/runoob-test/r_test.txt".
The file parameter can be an absolute or relative path; an absolute path is recommended, with the Windows path format D:\r_test.txt.
cat("RUNOOB", file="D:\\r_test.txt")
Note: This is an "overwrite" operation, so use it with caution because it clears the original data in the output file. If you want to "append", do not forget to set the append parameter:
cat("GOOGLE", file="/Users/runoob/runoob-test/r_test.txt", append=TRUE)
After running the above code, open r_test.txt; its content is as follows:
RUNOOBGOOGLE
sink()
The sink() function can write console output directly to a file:
sink("/Users/runoob/runoob-test/r_test.txt")
After this statement runs, any console output will be written to "/Users/runoob/runoob-test/r_test.txt" and will not be displayed in the console.
Note: This is also an "overwrite" operation and will directly clear the original file content.
If we still want to keep the console output, we can set the split attribute:
sink("/Users/runoob/runoob-test/r_test.txt", split=TRUE)
To cancel writing output to a file, you can call sink with no arguments:
sink()
Example
sink
(
"r_test.txt"
,
split
=
TRUE
)
Also output to the console
for
(
i
in
1
:
5
)
(
i
)
sink
(
)
Cancel output to file
sink
(
"r_test.txt"
,
append
=
TRUE
)
No console output, append to file
(
"RUNOOB"
)
After running the above code, an r_test.txt file is created in the current directory; its content is as follows:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] "RUNOOB"
Console output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Text input
We might think of scanf in C or java.util.Scanner in Java; if you have studied Python, you may be more familiar with the input() function. But as an interpreted language, R is more similar to some terminal scripting languages (such as bash or PowerShell), which are command-based and inherently require input and output and are not suited to developing user-facing applications (because they are themselves intended for end users). Therefore, R has no dedicated function for reading from the console; text input is always occurring in the use of R.
Reading text from a file
R has a rich set of file-reading functions, but if you simply want to read the contents of a file as a string, you can use the readLines function:
readLines("/Users/runoob/runoob-test/r_test.txt")
Execution result:
[1] "RUNOOBGOOGLE"
The result is two strings, corresponding to the two lines contained in the file that was read.
Note:Every line of the text file being read (including the last line) must end with a newline character, otherwise an error will occur.
Other methods
Besides simple text input and output, R provides many methods for inputting and outputting data. The most convenient feature of R is that data structures can be saved directly to files, with support for saving as CSV, Excel spreadsheets, and other formats, as well as direct reading. This is undoubtedly very convenient for mathematical researchers. However, these features have little impact on learning R, and we will cover them in later chapters.
Working directory
For file operations, we need to set the file path; R can get and set the current working directory using the following two functions:
- getwd() : Get the current working directory
- setwd() : Set the current working directory
Example
Current working directory
(
getwd
(
)
)
Set the current working directory
setwd
(
"/Users/runoob/runoob-test2"
)
View the current working directory
(
getwd
(
)
)
The output of the code above is:
[1] "/Users/runoob/runoob-test"
[1] "/Users/tianqixin/runoob-test2"
R's core feature: vectorization
This is one of R's most powerful aspects.
Python:
for i in range(10):
...
R:
x <- c(1,2,3)
x * 2
Result:
[1] 2 4 6
整个向量直接计算。
This makes R extremely powerful in the fields of mathematics, statistics, and data analysis.