💡 Intro. R Programming
R: An Interactive Data Object Computation Environment
■
Object
: Data of all type and structure are objects
■
Expression
: Combinations of object, operator and
functions
■ Computation
: Every expressions is
evaluated into an resultant object
■ Object Name
:
Every resultant object can be assigned to a name
■
Program
: A sequence of defining or updating objects
Object
An simple numeric
object
[1] 100
An numeric
vector
[1] 10 20 30
An character
vector
[1] "Amy" "Bob" "Candy"
Every object has it’s data type/class
and
str/strcture
(which will be elaborated latter.)
Expression
An object itself
[1] 100
Objects & Operators/Parentheses
[1] 11 12 13
Objects, Operators/Parentheses & Functions
[1] 3.317 3.464 3.606
Object Name
Assign the resultant object to the object name x
x
is a numeric vector
[1] 11 12 13
🌻
vector function
[1] 3.317 3.464 3.606
summary function
[1] 36
cascaded functions
[1] 0.5391
the pipe
operator %>%
[1] 0.5391
🌻
+
,-
,*
,/
,sqrt
,log
,exp
,…sum
,mean
,median
,max
,min
,…default
valuesF1
to see
the online helppipe
(%>%
) operator make it easier
to write/read cascaded function The most common mission of BA is to
The expected value of its outcome can be evaluated as
\[\pi = \sum_{i=1}^{n} p_i \times v_i \qquad(1)\]
Define \(v_i\) & \(p_i\) as numeric vectors v
and
p
Compose formula (1) as an expression and assign the result of
evaluation to object pi
🌻 Originally R was designed as an tool for p
and
v
are multiplied separately.
Print out the value of pi
[1] 5
📋 Now we can use the program
to evaluate the expected
outcome of any event, as long as we know its \(p_i\) and \(v_i\). For example …
[1] -19
📋 If we have list
object
cases = list(
case1 = data.frame(v = c(100, 50, -50, 0), p=c(0.1, 0.2, 0.3, 0.4)),
case2 = data.frame(v = c(-100, 50, 50), p=c(0.5, 0.4, 0.1)),
case3 = data.frame(v = c(50, -150), p=c(0.6, 0.4)),
case4 = data.frame(v = c(-100, -50, 0, 200), p=c(0.2, 0.2, 0.3, 0.3)),
case5 = data.frame(v = c(-70, 50, 80), p=c(0.1, 0.5, 0.4)),
case6 = data.frame(v = c(50, -150), p=c(0.4, 0.6))
)
Then, we can evaluate and compare their expected outcomes in a few lines of code.
par(cex=0.75)
sapply(cases, function(cs) sum(cs$p * cs$v) ) %>% sort %>%
barplot(main="Expected Outcomes")
abline(h=seq(-80,40,20),lty=3)