Block 1: Arithmetic and objects
Week 2 · Introduction to R · Imai §1.3.1–1.3.2 · about 12 min
NoteHow this works
Read the code and predict (write it down or tell your neighbour), answer the question, then run it with Run Code. Every cell is editable; Start Over resets it. Errors are information: read them.
1. Arithmetic
Run it. Then change a number and run it again.
2. Predict: overwriting an object
What does each of the three result lines print? Write down your guess, then run.
Read this code (it is not run yet):
result <- 5 + 3
result
result <- 5 - 3
resultPredict: What does the last line,
result, print?result <- 5 - 3 overwrites the old value; an object holds only its latest content.Now run it and compare with your answer:
3. Predict: Result vs. result
What is the difference between these two objects?
4. Change it: break it
What happens with Result + 1? With result + 1? Read the error message. What does it tell you?
Read this code (it is not run yet):
result <- 2
Result <- "5"
result + 1
Result + 1Predict: What does
Result + 1 do when Result is the text "5"?"5" in quotes is text, not a number. class() tells you what kind of object you have.Now run it and compare with your answer:
# "5" in quotes is text, not a number. class(Result) told you so.result <- 2
Result <- "5"
result + 1 # 3
as.numeric(Result) + 1 # 6: convert text to a number first
result <- 2
Result <- "5"
result + 1 # 3
as.numeric(Result) + 1 # 6: convert text to a number first