English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Generally, learning a new language starts with a program that outputs "Hello, World!". The R language "Hello, World!" program code is as follows:
myString <- "Hello, World!" print ( myString )
The above example assigns the string "Hello, World!" to the variable myString, and then uses the print() function to output.
Note:The R language uses the left arrow '<=' for assignment- The symbol, although some new versions also support the equal sign =.
Valid variable names in the R language are composed of letters, numbers, and the dots '.' or underscores '_'.
Variable names start with a letter or a dot.
Variable name | Is it correct? | Reason |
---|---|---|
var_name2. | Correct | It starts with a character and is composed of letters, numbers, underscores, and dots |
var_name% | Error | % is an illegal character |
2var_name | Error | Cannot start with a number |
.var_name, var.name | Correct | It can start with a dot '.', but pay attention that the dot '.' cannot be followed by a number |
.2var_name | Error | The dot '.' cannot be followed by a number |
_var_name | Error | Cannot start with an underscore _ |
The assignment of the latest version of the R language can use the left arrow '<='-、equals = 、right arrowhead -> Assignment:
# Use the equal sign = to assign > var.1 = c(0,1,2,3) > print(var.1) [1] 0 1 2 3 # Use the left arrowhead <-Assignment > var.2 <- c("learn","R") > print(var.2) [1] "learn" "R" # Use the right arrowhead <- Assignment > c(TRUE,1) -> var.3 > print(var.3) [1] 1 1
Variables defined can be viewed using ls() Function:
> print(ls()) [1] "var.1" "var.2" "var.3"
Variables can be deleted using rm() Function:
> rm(var.3) > print(ls()) [1] "var.1" "var.2" >
In the previous chapter, we have learned how to install the R programming environment. Next, we will introduce interactive programming and file script programming in R language.
We can enter the interactive programming window by executing the R command in the command line.
R
After executing this command, the R language interpreter will be called, and we can input the code after the > symbol.
Interactive commands can be exited by entering q():
> q() Save workspace image? [y/n/c]: y
The file extension of R language is .R.
Next, we create a w3codebox-test.R file: The code is as follows:
Next, we use Rscript in the command line window to execute the script:
Rscript w3codebox-test.R
The output result is as follows:
[1] "w3codebox"
The print() function is the output function in R language.
Like other programming languages, R language supports the output of numbers, characters, and so on.
The output statement is very simple:
print("w3codebox") print(123) print(3e2)
Execution Result:
[1] "w3codebox" [1] 123 [1] 300
Like node.js and Python, R language is an interpreted language, so we can often use R language as if it were a command line.
If we input a value on a single line, R will standardize and output it directly:
> 5e-2 [1] 0.05
If we need to concatenate the output, we can use the cat() function:
> cat(1, "add", 1, "equals", 2, '\n') 1 Add 1 Equals 2
The cat() function will automatically add a space between every two concatenated elements.
There are many ways to output to a file in R language, and it is very convenient.
The cat() function supports direct output of results to a file:
file parameter can be an absolute path or a relative path. It is recommended to use an absolute path, with the Windows path format as D:\\r_test.txt.3codebox", file="/Users/w3codebox/w3codebox-test/r_test.txt")
This statement will not produce any result in the console, but it will output "w3codebox" 输出到 "/Users/w3codebox/w3codebox-test/"}}
The output of "codebox" will be saved to the file "
file parameter can be an absolute path or a relative path. It is recommended to use an absolute path, with the Windows path format as D:\\r_test.txt.3cat("w
codebox", file="D:\\r_test.txt")
Note: This operation is a "overwrite write" operation, please use it with caution as it will clear the original data of the output file. If you want to "append write", do not forget to set the append parameter:/Users/w3codebox/w3codebox-test/cat("GOOGLE", file="
After executing the above code, the content of the r_test.txt file is as follows:
w3codeboxGOOGLE
The sink() function can directly output the text from the console to the file:
sink("/Users/w3codebox/w3codebox-test/r_test.txt")
After executing this statement, any output on the console will be written to the file "/Users/w3codebox/w3codebox-test/The output will not be displayed on the console. The content of the r_test.txt file is as follows:
Note: This operation is also a "overwrite write" operation, which will directly clear the original file content.
If we still want to retain the console output, we can set the split attribute:
sink("/Users/w3codebox/w3codebox-test/sink("r_test.txt", split=TRUE)
If you want to cancel output to the file, you can call the sink without any parameters:
sink()
sink("r_test.txt", split=TRUE) # The console also outputs for (i in 1:5) print(i) sink() # Cancel output to the file sink("r_test.txt", append=TRUE) # Do not output to the console, append to the file print("w3codebox")
After executing the above code, an r_test.txt file will be created in the current directory. The content of the file is as follows:
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] "w3codebox"
Console output is as follows:
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5
We may associate this with scanf in C language, java.util.Scanner in Java, or input() function if you have learned Python. However, R language itself, as an interpreted language, is more similar to some terminal script languages (such as bash or PowerShell), which are based on a command system and inherently require input and output, and are not suitable for developing user-oriented applications (as they are designed for end-users). Therefore, R language does not have a dedicated function to read from the console, and text input has always been ongoing in the use of R.
R language has a wealth of file reading functions, but if you simply want to read the content of a file into a string, you can use the readLines function:
readLines("/Users/w3codebox/w3codebox-test/r_test.txt")
Execution Result:
[1] "w3codeboxGOOGLE"
The read result is two strings, which are the two lines of content contained in the read file.
Note:The end of each line (including the last line) of the text file read must have a newline character, otherwise an error will occur.
In addition to simple input and output of text, R also provides many methods for inputting and outputting data. One of the most convenient features of R language is that it can directly save data structures to files, and supports saving in CSV, Excel table formats, and supports direct reading. This is undoubtedly very convenient for mathematical researchers. However, these features have little impact on the learning of R language, and we will mention them in subsequent chapters.
For file operations, we need to set the file path. R language can get and set the current working directory using the following two statements:
getwd() : Get current working directory
setwd() : Set current working directory
# Current working directory print(getwd()) # Set current working directory setwd("/Users/w3codebox/w3codebox-test2") # View current working directory print(getwd())
The output of the following code is:
[1] "/Users/w3codebox/w3codebox-test" [1] "/Users/tianqixin/w3codebox-test2"