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 <-"AAA"# text, always in quotesshares <-10# how many shares I holdprint(price) # -> [1] 185.4
[1] 185.4
print(ticker) # -> [1] "AAA" <- text prints with its quotes
[1] "AAA"
print(price * shares) # -> [1] 1854 <- the position valued in one line
[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 <- one number is still a vector
[1] 1
print(length(ticker)) # -> [1] 1 <- and so is one piece of text
[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" <- 10 is stored with decimals
[1] "numeric"
print(class(10L)) # -> [1] "integer" <- the L forces a whole number
[1] "integer"
print(class(price >180)) # -> [1] "logical" <- a comparison, not a number
[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.
tickers <-c("AAA", "CCC", "DDD") # three names held in one character vectorprices <-c(185.40, 410.20, 128.75) # one price per ticker, in that same ordershares <-c(10, 4, 20) # the holding that belongs to each tickerprint(tickers) # -> [1] "AAA" "CCC" "DDD"