Name a value with <-, check its type with class(), and multiply whole vectors of prices and share counts at once.
An object in R is a name for a value. You make one with <-.
In this lesson I name a price and a share count, ask R what type each one is, and then value a whole portfolio by multiplying two vectors.
Step 1. Name a value
<- puts the value on the right into the name on the left. R accepts = as well.
price <-185.40# a number with decimalsticker <-"AAPL"# text, always in quotesshares <-10# how many shares I holdprint(price) # -> [1] 185.4
[1] 185.4
print(ticker) # -> [1] "AAPL"
[1] "AAPL"
print(price * shares) # -> [1] 1854
[1] 1854
The [1] in front of every result is R telling you the line starts at the first element. Even a single number is a vector of length one:
print(length(price)) # -> [1] 1
[1] 1
print(length(ticker)) # -> [1] 1
[1] 1
Step 2. Ask what type it is
class(x) reports the type of what you stored. Numbers are "numeric", text is "character", TRUE and FALSE are "logical". Adding L to a whole number makes it an "integer".
print(class(price)) # -> [1] "numeric"
[1] "numeric"
print(class(ticker)) # -> [1] "character"
[1] "character"
print(class(shares)) # -> [1] "numeric"
[1] "numeric"
print(class(10L)) # -> [1] "integer"
[1] "integer"
print(class(price >180)) # -> [1] "logical"
[1] "logical"
shares <- 10 gives "numeric", not "integer", because R stores plain numbers with decimals underneath. Write 10L when you want a whole number.
Step 3. A portfolio in two vectors
c() combines several values into one vector. Arithmetic on two vectors runs element by element, so the first price meets the first share count, the second the second. No loop.