R-Studio Funzioni
R-Studio Funzioni
Diego Battagliese
30 settembre 2021
R (from Wikipedia)
R is a programming language and free software environment for statistical computing and graphics. The
R language is widely used among statisticians and data miners for developing statistical software and data
analysis. Polls, surveys of data miners, and studies of scholarly literature databases show that R’s popularity
has increased substantially in recent years. As of August 2018, R ranks 18th in the TIOBE index, a measure of
popularity of programming languages. Although R has a command line interface, there are several graphical
front-ends, most notably RStudio.
R is a calculator
2+2
## [1] 4
The standard assignment operator in R is " <- " or " = " You can use both symbols indiscriminately.
Let’s start with R objects.
a=2+2
a
## [1] 4
b=2*a
You have already noted that we use # to write comments in your script file. All commands written after #
will not be executed
a # print out a
GETTING HELP
Several resources are available to help you learn more about R. These include several facilities WITHIN R
itself and, of course, on the Web.
The help() Function: if you have problems with a particular function (e.g. sum), you can get online help
typying
help(mean)
For special characters and some reserved words you must use “”
For example, if you have problems with “<” operator type
1
help("<")
# or
?"<"
For example, if you need help for the reserved word “if” (basic control-flow constructs see later), type
help("if")
# or
?"if"
The example() Function If you do not need all help information but only sum example use the example()
function.
example(mean)
##
## mean> x <- c(0:10, 50)
##
## mean> xm <- mean(x)
##
## mean> c(xm, mean(x, trim = 0.10))
## [1] 8.75 5.50
example("if")
##
## if> for(i in 1:5) print(1:i)
## [1] 1
## [1] 1 2
## [1] 1 2 3
## [1] 1 2 3 4
## [1] 1 2 3 4 5
##
## if> for(n in c(2,5,10,20,50)) {
## if+ x <- stats::rnorm(n)
## if+ cat(n, ": ", sum(x^2), "\n", sep = "")
## if+ }
## 2: 0.7147026
## 5: 5.609109
## 10: 7.297628
## 20: 17.89645
## 50: 45.61336
##
## if> f <- factor(sample(letters[1:5], 10, replace = TRUE))
##
## if> for(i in unique(f)) print(i)
## [1] "d"
## [1] "b"
## [1] "a"
## [1] "c"
## [1] "e"
The help.search() Function
The help() and example() functions help you when you already know the name of the function you would like
to use. If you don’t know what you are looking for, you can use the help.search() function, a Google-style
search through R documentation.
2
For instance, say you need a function to draw three-dimensional plots. Type
help.search("3d plots")
# or
??"3d plots"
R finds the packages that could contain functions for drawing 3d plots.
Help for packages: you can also learn about entire packages typing help(package=PACKAGE’s NAME)
For example, for the package “graphics”
help(package=graphics)
Numerical operations
help(Arithmetic)
help(Logarithm)
## [1] "C:/Users/diego/Desktop"
Check that your working directory contains the objects you created in the previous working session
ls()
Packages:
How to load packages and install packages from RStudio.
R variable types are called modes.
In the next sections we will see different R modes.
Let’s start with simple R objects and their modes.
3
[1] MODE: NUMERIC (numeric {[integer, real] o complex})
—————————————————————
a=10
b=15.53
d=3.51+1.2i
## [1] "numeric"
mode(b)
## [1] "numeric"
mode(d)
## [1] "complex"
## [1] "character"
## [1] "logical"
VECTORS
Vectors are created using the concatenating function “c”.
Vector of numbers
v1=c(5,2,3,1,9)
v1
## [1] 5 2 3 1 9
mode(v1)
## [1] "numeric"
Vector of characters
4
v2=c("a","b","c")
v2
## [1] "character"
Vector of “objects”
v3=c(a,b,d)
v4=c(g,h,i,l)
mode(v4)
## [1] "logical"
An empty vector
v5=c()
Individual elements of a vector are accessed via [“position of the element”]. For example if you want to select
the second element of v1,
v1[2]
## [1] 2
Subsetting is a very important operation on vectors. If you want to select a subset of consecutive elements of
the vector type [“position of the first element” : “position of the last element”]
For example, if you want to select from the second and the fourth element of v1
v1[2:4]
## [1] 2 3 1
v1
## [1] 5 2 3 1 9
If you want to select elements in non consecutive positions you type
[c(“position 1”,“position 2”,“position 3”)] For example, if you want to select elements of position 3,2,5 of v1
v1[c(3,2,5)]
## [1] 3 2 9
How many elements in your vector?
length(v1)
## [1] 5
You can also execute simple operations using your vectors
sum(v1)
## [1] 20
mean(v1)
## [1] 4
prod(v1)
5
## [1] 270
cumsum(v1)
## [1] 5 7 10 11 20
v1-2
## [1] 3 0 1 -1 7
v1/2
## [1] 2 2 0 1 0
# the integer division
v1%/%3
## [1] 1 0 1 0 3
Simple operations with vectors:
When applying an operation to two vectors that requires them to be the same length, R automatically
recycles, or repeats, the shorter one, until it is long enough to match the longer one
c(2,4,1)+c(5,1,2,0,0,4)
## [1] 7 5 3 2 4 5
# that is equal to
c(2,4,1,2,4,1)+c(5,1,2,0,0,4)
## [1] 7 5 3 2 4 5
v1*c(5,2)
## [1] 25 4 15 2 45
Vectors contain objects of the same mode. If you concatenate elements of different modes . . .
new.1=c(v1,v2)
mode(new.1)
## [1] "character"
new.2=c(v1,v2,v3,g,h,v4)
new.2
6
mode(new.2)
## [1] "character"
Change the mode of a vector
as.character(v1)
## [1] 1 0 0 1
as.numeric(v2)
## [[1]]
## [1] "Hallo" "Friends" "Hallo"
##
## [[2]]
## [1] 30.0 50.0 0.5 0.1
##
## [[3]]
## [1] TRUE TRUE FALSE
mode(list.1)
## [1] "list"
How to access to list elements?
Solution 1: if the elements of the list do not have a name as in list.1, just type the position using [[]]
list.1[[1]]
## [1] "Hallo"
7
list.1[[1]][2]
## [1] "Friends"
list.1[[1]][c(1,3)]
## [1] 0.1
list.1[[2]][1:3]
## $welcome
## [1] "Hallo" "Friends" "Hallo"
##
## $mynumbers
## [1] 30.0 50.0 0.5 0.1
##
## $myidea
## [1] TRUE TRUE FALSE
list.2[[1]]
8
mode(help)
## [1] "function"
mode(sum)
## [1] "function"
A function is a group of instructions that takes inputs, uses them to compute other values, and returns a
results.
function.name=function(input values){ out=operations involving input values to obtain the output value
return(out) }
Example 1: simple function with no input
hallo=function(){
print("HALLO WORLD")
}
## [1] 28.27
Example 3: counts the number of odd integers in a vector
oddcount=function(x){
mod=x%%2
count=sum(mod)
return(count)
}
check:
oddcount(x=c(1,2,3,7,9))
## [1] 4
oddcount(x=c(1,2,5,1))
## [1] 3
And for counting the even numbers in a vector? Let’s try by yourself!
How to use an R function: arguments, order and default
Consider this simple function:
9
sum.val=function(x,y,z){
s=(x-y)/z
return(s)
}
# Argument: x, y and z
# Order: 1. x, 2. y and 3. z
Then
sum.val(x=6,y=3,z=2) # ok! this is equivalent to
## [1] 1.5
sum.val(z=2,x=6,y=3)
## [1] 1.5
# and to
sum.val(6,3,2)
## [1] 1.5
# BUT not equal to
sum.val(2,6,3)
## [1] -1.333333
When you use a function (R function or your function) remember that:
: the arguments of the function MUST be written in the same order used in the definition of the function : you
can omit the name of the arguments if you are SURE that you are using the right order (see sum.val(6,3,2))
*: if you write the name of the arguments, it is not necessary to write them in the order specified in the
function definition (see sum.val(x=6,y=3,z=2) and sum.val(z=2,x=6,y=3))
## function(x,y,z){
## s=(x-y)/z
## return(s)
## }
## <bytecode: 0x0000000034ac65e8>
10
rm("a")
Check:
ls()
## [1] 15.53
# .... ok, "b" is still there
new=5+5
b=new
b
## [1] 10
# .... ok ... but the "old" "b"? Lost....
If you want to remove, some objects from the workspace, use the function rm as follows:
rm(list=c("b","new"))
ls()
11