Easy Tutorial
❮ R Mysql Connect R Data Types ❯

Basic R Language

Learning a new language typically starts with a "Hello, World!" program. The R language "Hello, World!" program code is as follows:

Example (helloworld.R)

myString <- "Hello, World!"

print ( myString )

The above example assigns the string "Hello, World!" to the variable myString and then outputs it using the print() function.

Note: The R language uses the left arrow <- for assignment, although some newer versions also support the equal sign =.

Variables

Valid variable names in R consist of letters, digits, periods ., or underscores _.

Variable names start with a letter or a period.

Variable Name Correct Reason
var_name2. Correct Starts with a letter and consists of letters, digits, underscores, and periods
var_name% Incorrect % is an illegal character
2var_name Incorrect Cannot start with a digit
.var_name, var.name Correct Can start with a period, but a period followed by a digit is not allowed
.2var_name Incorrect A period followed by a digit is not allowed
_var_name Incorrect Cannot start with an underscore

Variable Assignment

The latest versions of R support assignment using the left arrow <-, equal sign =, and right arrow ->:

Example

# Using the equal sign = for assignment
> var.1 = c(0,1,2,3)           
> print(var.1)
[1] 0 1 2 3

# Using the left arrow <- for assignment
> var.2 <- c("learn","R")   
> print(var.2)
[1] "learn" "R"

# Using the right arrow -> for assignment
> c(TRUE,1) -> var.3
> print(var.3)
[1] 1 1

To view defined variables, you can use the ls() function:

Example

> print(ls())
[1] "var.1" "var.2" "var.3"

To delete variables, you can use the rm() function:

Example

> rm(var.3)
> print(ls())
[1] "var.1" "var.2"
>

In the previous chapter, we learned how to install the R programming environment. Next, we will introduce interactive and script file programming in R.

Interactive Programming

You can enter the interactive programming window by executing the R command in the command line:

R

This command will invoke the R interpreter, and you can input code after the > prompt.

You can exit the interactive command by typing q():

> q()
Save workspace image? [y/n/c]: y

Script File

R language files have the .R extension.

Next, we create a tutorialpro-test.R file with the following code:

tutorialpro-test.R File

myString <- "tutorialpro"

print ( myString )

We can execute this script in the command line window using Rscript:

Rscript tutorialpro-test.R

The output is as follows:

[1] "tutorialpro"

Input and Output

print() Output

print() is the output function in R.

Like other programming languages, R supports output of numbers, characters, etc.

The output statement is straightforward:

print("tutorialpro")
print(123)
print(3e2)

Execution result:

[1] "tutorialpro"
[1] 123
[1] 300

Similar to node.js and Python, R is an interpreted language, so we often use it like a command line.

If we input a value on a single line, R will output it directly:

> 5e-2
[1] 0.05

cat() Function

For concatenating output, you can use the cat() function:

Example

> cat(1, "加", 1, "等于", 2, '\n')
1 加 1 等于 2

The cat() function automatically adds spaces between concatenated elements.

Output to a File

R offers various and convenient methods to output content to a file.

The cat() function supports direct output to a file:

cat("tutorialpro", file="/Users/tutorialpro/tutorialpro-test/r_test.txt")

This statement does not produce results in the console but instead outputs "tutorialpro" to the "/Users/tutorialpro/tutorialpro-test/r_test.txt" file.

The file parameter can be an absolute or relative path; it is recommended to use an absolute path. The Windows path format is D:\\r_test.txt.

cat("tutorialpro", file="D:\\r_test.txt")

Note: This operation is an "overwrite" operation and should be used with caution as it will clear the existing data in the output file. If you want to "append" instead, do not forget to set the append parameter:

cat("GOOGLE", file="/Users/tutorialpro/tutorialpro-test/r_test.txt", append=TRUE)

After executing the above code, opening the r_test.txt file will show the following content:

tutorialproGOOGLE

sink()

The sink() function can direct text output from the console directly to a file:

sink("/Users/tutorialpro/tutorialpro-test/r_test.txt")

After this statement is executed, any output on the console will be written to the "/Users/tutorialpro/tutorialpro-test/r_test.txt" file, and the console will not display the output.

Note: This operation is also an "overwrite" operation and will directly clear the existing file content.

If we still want to retain console output, we can set the split attribute:

sink("/Users/tutorialpro/tutorialpro-test/r_test.txt", split=TRUE)

To cancel output to the file, you can call sink() with no parameters:

sink()

Example

sink("r_test.txt", split=TRUE)  # Console output is also shown
for (i in 1:5) 
    print(i)
sink()   # Cancel output to file

sink("r_test.txt", append=TRUE) # Console output is not shown, append to file
print("tutorialpro")

Executing the above code will produce an r_test.txt file in the current directory with the following content:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] "tutorialpro"

Console output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Text Input

You might think of functions like scanf in C, java.util.Scanner in Java, or input() in Python. However, as an interpreted language, R is more akin to command-line scripting languages like bash or PowerShell, which are inherently command-based and require input and output, and are not suitable for developing user-facing applications as they are intended for end-user use. Therefore, R does not have a dedicated function for reading from the console; text input is ongoing in R usage.

Reading Text from a File

R has a rich set of functions for reading files, but if you want to read the content of a file as a string, you can use the readLines function:

readLines("/Users/tutorialpro/tutorialpro-test/r_test.txt")

Execution result:

[1] "tutorialproGOOGLE"

The reading result is two strings, corresponding to the two lines of content in the file.

>

Note: Each line in the text file (including the last line) must end with a newline character, otherwise an error will occur.

Other Methods

In addition to simple input and output, R provides many ways to input and output data. One of the most convenient features of R is the ability to directly save data structures to files, supporting formats like CSV and Excel, and direct reading. This is undoubtedly very convenient for mathematical researchers. However, these functions have little impact on learning R, and we will cover them in later chapters.

Working Directory

For file operations, we need to set file paths. R provides the following two functions to get and set the current working directory:

Example

# Current working directory
print(getwd())

# Set current working directory
setwd("/Users/tutorialpro/tutorialpro-test2")

# View current working directory
print(getwd())

Executing the above code outputs the following result:

[1] "/Users/tutorialpro/tutorialpro-test"

[1] "/Users/tianqixin/tutorialpro-test2"

❮ R Mysql Connect R Data Types ❯