Making R Speak
The simplest way to make R "speak" is by asking it to print something. Anything inside quotes is treated as text. Without quotes, R thinks it is a number or piece of code.
Printing Text
What it means:
Printing text in R means to display words, messages, or results in the console. It is useful for checking your code, showing results, and giviing feedback during a program.
How it works:
To write text values in R, you need to surround your words in quotation marks in the console and press Enter. R will then automatically display the output.
Printing Text Example:
> "Good Morning"
[1] "Good Morning"
The [1] in the output is an index number. This represents the first element of the output. R uses this to evaluate what you type and print the output by default.
> Good Morning
Error: unexpected symbol in "Good Morning"
The phrase without quotation marks triggers an error because R tries to read it as a command, not as text.
🧠 Try It!
Open RStudio and type the following lines. What happens when you remove the quotation marks?
"R is fun!"
> R is fun!
Printing Numbers
Unlike text, numbers do not need quotes. If it is written with quotes, it would be treated as texts instead of a number.
Example: Printing Numbers
> 3
[1] 3
> 6 + 10
[1] 16
🧠 Practice in RStudio
Try these in RStudio:
5 * 8
100 / 5
2 ^ 4
What do you notice about how R shows results?
Using the print() Function
Although R automatically prints results, the print() function is another method of outputting data. The print() function gives you more control over the output. It does this by not automatically showing an output unless you use
Ways to Use Print()
It used when you need explicit output inside complex code, such as loops or conditional statements.
> print("Hello, my name is...")
[1] "Hello, my name is..."
Using print() with Complex Code
The print() function allows you to print every iteration's result is visible. In the example below, you will see that the print() function prints every number in the loop rather than just the last element in the loop.
Example 3: Using print() in a Loop
> for (x in 1:5) { print(x) }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
🧠 Concept Check
Which of the following will correctly output a number in R? (Select all that apply)
Mini Project: R Introduction Card
In RStudio, create a short self-introduction using print statements. Include:
- Your name
- Your favorite sport or hobby
- One math operation that outputs a number
#Example Introduction Card
print("Hello! My name is Josh")
print("I love soccer and watching tv!")
print(5 + 7)