R is a command-line language, which means that you type commands into the console and R responds with output. Commands in R typically involve calling functions to run on objects Objects are created using assignment statements Try typing these examples in the console. Hit enter after typing a command to run it:
x <- 5
y = 7
z = x + y
print(x * y); print(z)
x == 5
x == y
x != y
word1 = "hello"
word2 = "world"
word3 = paste(word1, word2)
print(word3)
# this line is a comment
R is case sensitive. Variable names cannot start with numbers or have spaces. Try running these examples that will give errors
#these will have errors
a = 10
print(A)
4w = 99
new word = "words"
#Fixes:
w4 = 99
new_word = "words"
newWord = "words2"
R has many built-in functions that can make things much easier!
Try some of these examples by running them in an R Script.
Go to File > New File > R Script to make an empty script, and then type this text. Hitting enter in here moves you to a new line.
To run a line of code, click on it and hit Ctrl + Enter (Windows) or Command + Enter (Mac), or click “Run”. To run multiple lines, highlight them and then hit Ctrl + Enter, Command + Enter, or “Run”
cat("first", "word")
numbers = c(12, 13.72, 86.002)
length(numbers)
mean(numbers)
sd(numbers)
str(numbers)
summary(numbers)
View(numbers)
Sometimes you only want R to run commands under certain conditions. Try this example. This code only prints “yes” if the value you are checking is equal to 5.
x <- 5
if(x == 5) {
print("Yes")
} else {
print("No")}
You can also use loops to perform actions a set number of times. Say for example, you wanted to count how many times a subject’s response was equal to 5…
tally = 0
data <- c(3,1,5,2,2,5,4,5)
#the c() function creates a vector (like a column)
for (x in 1:length(data)){
#run x times, from 1 to the end of the #data vector
if (data[x] == 5) {
tally = tally + 1
print("yes")
}
else {
print ("no")
}
}
print(tally)