0% found this document useful (0 votes)
43 views11 pages

R-Studio Funzioni

R is a widely used programming language and software environment for statistical analysis and graphics. It has a command line interface but also graphical front-ends like RStudio. R can be used to perform calculations, create visualizations, and develop statistical software. Help and documentation for R functions and packages can be accessed within R. R supports different data types like numeric, character, and list, and users can write their own functions in R.

Uploaded by

Luigi Gigli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views11 pages

R-Studio Funzioni

R is a widely used programming language and software environment for statistical analysis and graphics. It has a command line interface but also graphical front-ends like RStudio. R can be used to perform calculations, create visualizations, and develop statistical software. Help and documentation for R functions and packages can be accessed within R. R supports different data types like numeric, character, and list, and users can write their own functions in R.

Uploaded by

Luigi Gigli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Prima lezione su R

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)

## starting httpd help server ... done


# or
?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)

## No documentation for 'Logarithm' in specified packages and libraries:


## you could try '??Logarithm'
help.search("Logarithm")
help(sqrt)
help(Trig)
help(Special)

CLOSE and SAVE our work in the working directory:


.Rdata file: it is the saved workspace, containing all objects you created .Rhistory file: it records your
commands, to remind you how that workspace was created.

What is the working directory and how to set it.


Get the working directory:
getwd()

## [1] "C:/Users/diego/Desktop"
Check that your working directory contains the objects you created in the previous working session
ls()

## [1] "a" "b" "f" "i" "n" "x" "xm"

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

check the mode of the objects


mode(a)

## [1] "numeric"
mode(b)

## [1] "numeric"
mode(d)

## [1] "complex"

[2] MODE: CHARACTERS


e="Hallo"
f="World"
mode(e)

## [1] "character"

[3] MODE: LOGICAL


g=TRUE
h=FALSE
i=F
l=T
mode(g)

## [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] "a" "b" "c"


mode(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.5 1.0 1.5 0.5 4.5


# the mod operator is "%%"
v1%%3

## [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)

## Warning in v1 * c(5, 2): longer object length is not a multiple of shorter


## object length
## [1] 25 4 15 2 45
# that is equal to
v1*c(5,2,5,2,5)

## [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

## [1] "5" "2" "3" "1" "9"


## [6] "a" "b" "c" "10+0i" "15.53+0i"
## [11] "3.51+1.2i" "TRUE" "FALSE" "TRUE" "FALSE"
## [16] "FALSE" "TRUE"

6
mode(new.2)

## [1] "character"
Change the mode of a vector
as.character(v1)

## [1] "5" "2" "3" "1" "9"


as.character(v3)

## [1] "10+0i" "15.53+0i" "3.51+1.2i"


as.character(v4)

## [1] "TRUE" "FALSE" "FALSE" "TRUE"


as.numeric(v4)

## [1] 1 0 0 1
as.numeric(v2)

## Warning: si è prodotto un NA per coercizione


## [1] NA NA NA
# .... what happens???

[4] MODE: LIST


One simple solution to put elements of different modes together without changing their modes!
A list is a container for items of different data types.
list.1=
list(c("Hallo","Friends","Hallo"),c(30,50,0.5,0.1),c(TRUE,TRUE,FALSE))
list.1

## [[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" "Friends" "Hallo"


list.1[[1]][1]

## [1] "Hallo"

7
list.1[[1]][2]

## [1] "Friends"
list.1[[1]][c(1,3)]

## [1] "Hallo" "Hallo"


list.1[[2]]

## [1] 30.0 50.0 0.5 0.1


list.1[[2]][4]

## [1] 0.1
list.1[[2]][1:3]

## [1] 30.0 50.0 0.5


list.1[[2]][c(1,4)]

## [1] 30.0 0.1


Solution 2: if the elements of the list have a name, you can directly access them using the symbol $
list.2=list(welcome=c("Hallo","Friends","Hallo"),
mynumbers=c(30,50,0.5,0.1),
myidea=c(TRUE,TRUE,FALSE))
list.2

## $welcome
## [1] "Hallo" "Friends" "Hallo"
##
## $mynumbers
## [1] 30.0 50.0 0.5 0.1
##
## $myidea
## [1] TRUE TRUE FALSE
list.2[[1]]

## [1] "Hallo" "Friends" "Hallo"


# is equivalent to
list.2$welcome

## [1] "Hallo" "Friends" "Hallo"


list.2[[1]][c(1,3)]

## [1] "Hallo" "Hallo"


list.2$welcome[c(1,3)]

## [1] "Hallo" "Hallo"

[5] MODE: FUNCTION


As in most programming languages, you can write or customize your own R function or change existing
functions.

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")
}

execute the function


hallo()

## [1] "HALLO WORLD"


Example 2: write a function that compute the area of a circle (one argument)
area.circle=function(radius){
out=(radius^2)*pi
return(round(out, digits=2))
}

Now compute the area of a circle with radius equal to 3


area.circle(radius=3)

## [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))

How to customize an existing function in R?


This is the advantage of the open source! You have already noted that you can see the code generating a
function by directly typing its name
For our simple function
sum.val

## function(x,y,z){
## s=(x-y)/z
## return(s)
## }
## <bytecode: 0x0000000034ac65e8>

Now stop for a while and clean our workspace


Remove Objects and Clean the workspace
If you want to remove an object from your workspace use the function
rm(“object name”).
For example remove “a” typing

10
rm("a")

Check:
ls()

## [1] "area.circle" "b" "d" "e" "f"


## [6] "g" "h" "hallo" "i" "l"
## [11] "list.1" "list.2" "n" "new.1" "new.2"
## [16] "oddcount" "sum.val" "v1" "v2" "v3"
## [21] "v4" "v5" "x" "xm"
DANGER!
If you remove or rename an object, it cannot be retrieved!
# .... "a" cannot be found!
b

## [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()

## [1] "area.circle" "d" "e" "f" "g"


## [6] "h" "hallo" "i" "l" "list.1"
## [11] "list.2" "n" "new.1" "new.2" "oddcount"
## [16] "sum.val" "v1" "v2" "v3" "v4"
## [21] "v5" "x" "xm"
To remove all objects
rm(list=ls())

11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy