---
title: "1.Introduction to R"
author: "T. Monleon (University of Barcelona)"
date: "DIA 1 - 2024"
output:
  pdf_document:
    number_sections: yes
    toc: yes
    toc_depth: 5
  word_document:
    toc: yes
    toc_depth: 5
---


```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.pos = 'h',
                      echo=TRUE, eval=TRUE, warning=FALSE, message=FALSE)
```

Los ejercicios y ejemplos proporcionados en este apartado se basan en materiales propios y de acceso libre, y su único propósito es el uso docente.
Se ha hecho un esfuerzo para garantizar la precisión y confiabilidad de la información, sin embargo, es importante tener en cuenta que la información puede cambiar con el tiempo.
Se recomienda a los usuarios que consulten fuentes adicionales y verifiquen la información por sí mismos antes de tomar cualquier decisión o acción basada en la información proporcionada aquí.



# Introduction to R

In this course, we will use the programming language R, which is a commonly used language for statistical analysis. One of the main advantages of R is that there is a huge repository, the Comprehensive R Archive Network (CRAN https://cran.r-project.org), where you will find free packages to do many statistical analysis. Another repository is Bioconductor (https://www.bioconductor.org), which is mainly a set of bioinformatics R packages to solve medical, biological problems and work with different types of data like high throughput genomic data.

We will use the Rstudio graphical interface to write and run our scripts, it is the most commonly used interface for R programming, simple and clean! The command line is the R interface, every time you enter a command you'll get a result.


## Install R and Rstudio

R and Rstudio are installed in the university computers. But if you still don't have R or Rstudio in your system, we recommend you to install them. Both are very easy to install, just download the binaries and then follow the steps they ask you to do.

1. To install R go to <https://cran.rstudio.com> and download the version you need for Linux, Mac or Windows.

2. Finally install Rstudio by downloading the version you need: <https://www.rstudio.com/products/rstudio/download/>


## Install and load packages

As we mentioned earlier, the main advantage of R is the big amount of packages available for free. The two main package repositories are CRAN and Bioconductor, and there is a specific way of installing packages from one or the other.

### From CRAN

To install new packages from CRAN we just have to use the functions **install.packages()** and **library()**. Let's imagine we want to install the fun package:

root access:
```{r, eval=FALSE}
#install locally and automatically in
install.packages("fun", repos="http://cran.r-project.org")   
# the package will be automatically installed if we have root access (e.g your computer)
````

Now install in the specific location:
```{r}
install.packages("fun", lib="C:/Users/bootstrap3/Desktop/R-packages",
                 repos="http://cran.r-project.org") 
# if you don't have root access (e.g university's computers) you have to 
# install it locally in the computer in a specific location.

#See in tab Packages, fun. Examples and functions.
```


Remember that if you want to use an R package you must not only have installed it locally but you must also load it during the session. This improves R efficiency because you don't need to load all packages in every session but you have to remember to load the ones you need.

```{r , eval=FALSE}
library("fun")    
# once the package is installed, we have to load the library containing all 
# fun functions in order to use it

# without root access, you are loading the package from the local directory 
# where you previously installed it.

#library("fun",lib.loc="C:/Users/bootstrap3/Desktop/R-packages")  
# without root access, you are loading the package from the local directory 
# where you previously installed it.

```

There is another way if you're using Rstudio, the previous commands will work but you can also try clicking "Tools" in the Rstudio menu bar and then "Install Packages..". You just need to type the name of the package and it will be installed. Note that only packages from the CRAN repository can be installed this way.

Install alternative package version. See all packages in 
https://cran.r-project.org/web/packages/index.html 

and packages by name: https://cran.r-project.org/web/packages/available_packages_by_name.html 

```{r}
#example: Intall previous version of tidyverse
#Seek package in CRAN
#https://cran.r-project.org/web/packages/tidyverse/index.html 
#old source: Old sources:	tidyverse archive in https://cran.r-project.org/
#take care of all dependencies

#install previous versions: https://support.posit.co/hc/en-us/articles/219949047-Installing-older-versions-of-packages


```


### From Bioconductor

The bioconductor packages have to be installed by a special procedure. First, the **if (!requireNamespace("BiocManager"))** command will run an R script that installs a core set of Bioconductor packages (it might take a while) and then you can install new Bioconductor packages just by typing **BiocManager**. Like before, we use **library("package")** to load the installed package.

ATTENTION IF YOU INSTALL BIOCONDUCTOR, IT MAY TAKE A CERTAIN TIME. IT IS VERY COMPUTATIONALLY COSTLY

```{r}
#if (!requireNamespace("BiocManager"))
#install.packages("BiocManager")
#BiocManager::install("GenomicFeatures")
```


```{r , eval=FALSE}

#if (!requireNamespace("BiocManager"))
#install.packages("BiocManager") # installs Bioconductor core packages

#install one library
#BiocManager::install("GenomicFeatures") #install library GenomicFeatures, see at http://bioconductor.org/packages/release/bioc/html/GenomicFeatures.html

#see more information in: https://www.datacamp.com/tutorial/intro-bioconductor

#install two libraries
#BiocManager::install(c("GenomicFeatures", "AnnotationDbi")) 
# after installing Bioconductor, you can install other packages within Bioconductor

#library("GenomicFeatures") # always remember to load the library!

````


Motivating example of what can be done with R
R Shiny
```{r}
#see in http://www.graphbio1.com/en/ 
#automatic analysis
```

##Elementos básicos del lenguaje:

Objetos: Los objetos son las unidades básicas de datos en R. Pueden ser números, vectores, matrices, data frames, listas, funciones, etc.
Expresiones: Las expresiones son combinaciones de objetos y operadores que producen un valor. Las expresiones pueden ser aritméticas, lógicas, de asignación, etc.
Sentencias: Las sentencias son instrucciones que le dicen a R qué hacer. Las sentencias pueden ser simples, como asignar un valor a una variable, o compuestas, como un bucle o una función condicional.

Tipos de datos:
R tiene una variedad de tipos de datos para representar 
diferentes tipos de información:
Numéricos:Números enteros y reales.
Caracteres:Cadenas de texto.
Lógicos:Verdadero o falso.
Factores:Categorías discretas.
Fechas y horas:Fechas y horas específicas.
Complejos:Números complejos.

Estructuras de datos:
R proporciona diferentes estructuras de datos para organizar y almacenar información:
Vectores:Un vector es una colección unidimensional de objetos del mismo tipo.
Matrices:Una matriz es una colección bidimensional de objetos del mismo tipo.
Data frames:Un data frame es una tabla de datos que contiene variables de diferentes tipos.
Listas:Una lista es una colección flexible de objetos de diferentes tipos.



## Basic R programming 

We can type R commands in the R console of Rstudio after the ">" symbol and the command is executed after hitting the Return key. Here are some simple examples to start:

### A quick start

R can work as a calculator: 

```{r}
1         # typing 1 simply returns the number
"a"       # strings are quoted in R, typing a string will return the string
5+5       # you can do mathematical operations directly typing them in the console
sqrt(9)   # built-in function square root

#The calculation (1 + 1) is performed first. Then, (2 / 2) is calculated, fol-lowed by 1 * 1. Whereas if this operation were written without parenthesis the output would be as follows:
 1 * 2 / 1 + 1

```

We can codify variables by giving them a name and storing information inside using "<-"  

```{r}
a <- 2         #numeric
b <- "string"  #character
a              #show a 
```

There are several types of objects in R (data structures); the most common is a *vector*. A vector is the union of several elements. To concatenate (put together) several elements into a vector, we just have to write our elements into the function called **c()**:

```{r}
numbers <- c(10,5,46,7,3) ## remember this function!!
numbers
letters<-c("A","B","C","D","B") #string
letters
logic<-c(T,F,T,F,T,F)
logic
```
 
### Built-in functions

Similarly to other programming languages, R also has built-in functions. All functions have arguments that can modify the behaviour of the function. 
You can have a description of each of the functions and their usage if you type **?setwd()** or **help(setwd)**.

Here are some useful R functions. First, to know in which directory (folder) are we working:

```{r, eval=FALSE}
getwd()     # getwd() returns the current path
?setwd      # help about the function setwd
help(setwd)

#changes to another path using sentence:
#setwd("~/Documents/IL3_DS_2023")     # changes to another path. 

```

Another way is to go the panel Files, navigate to a given folder and then press More --> Set as a working directory. 


```{r}
str(numbers) #show structure of an object (see the same in the panel Enviroment/Values)

class(numbers) #show type of data
length(numbers) # lenght of the vector
sum(numbers)    # sum the elements of the vector
mean(numbers)   # mean value of the vector
sd(numbers)     # SD value of the vector
min(numbers)    # minimum value of the vector
max(numbers)    # maximum value of the vector
sort(numbers)   # default sorting is increasing
sort(numbers,decreasing = TRUE)  # change the default

order(numbers) 
# this function returns a vector of values representing the order of observations
# it gives you the index
# Here default sorting is decreasing!
```

In this later case, it tells you that the element in the fifth position, which in the vector numbers is 3, is the first element of the ordered vector of numbers. If we wanted the list of numbers already sorted then:

```{r}
numbers[order(numbers)]

#other possibility
sort(numbers)
```

### Example: Guess the functions

Can you guess what these functions can do? Take a few minutes and play with them using the variables that we created before or new ones, you'll see that you are going to use them quite often!

```{r , eval=FALSE}
summary()
range()
seq()
rep()
unique()
log()
paste()
setdiff()

```


```{r , eval=T}
# some examples
summary(numbers)    # summary statistics
range(numbers)      # min and maximum value of a vector
seq(from = 2,to = 20,by = 5)  # sequence of numbers
rep("data",5)         # repeat something a number of times
unique(letters)     # return the unique values
log(numbers,base = 10)  # apply a logaritm
paste(letters,numbers,sep = "-")  # paste elements together

othernumbers <- c(12,7,5,43,38)
setdiff(othernumbers,numbers)   # difference of sets 
# gives the elements of vector 1 that are not in vector 2

```



### Indexing 

To access specific values of your variables you can use basic indexing. 

```{r }
numbers[1]    # in R, vectors start with 1!
numbers[1:3]  # from element 1 to 3
numbers[-2]   # all elements except the one in position 2
numbers[c(1,5)]  # elements 3 and 5
```

### Data frames

The second most common object in R is a data frame. Data frames or datasets are just a grouping of vectors.

Now imagine a hospital data about floors and rooms.

```{r }
hospital <- data.frame(floor=numbers, room=letters)  
hospital
#show(hospital) #to see in a new window the data frame
#fix(hospital)
```

We used the **data.frame()** function to create a new dataframe with two variables called floor and room with values from variables from the vectors numbers and letters.

If you want to get a specific column of a data frame we use $, or we can also access it by indexing. If you use indexing be aware that data frames have two indexes: [row,column]. You can use this nomenclature when you're indexing to get a subset of your data:

* == (equal)
* != (not equal)
* < (lower than)
* \> (higher than) 
* & (AND)
* \| (OR)

```{r }
hospital$floor    # outputs the column named floor
hospital[,1]      # outputs first column (same result as before)
hospital[1,]      # outputs the first row
hospital[hospital$floor==10,]  # outputs the row where floor is equal 10
hospital[hospital$floor > 7 ,]  # outputs rows where floor is higher than 7
hospital[hospital$floor > 7 &  hospital$room == "A" ,]  
# outputs rows where floor is higher than 7 AND the room equals A
```

As a data frame has two dimensions (rows, columns) there is a function called **dim()** that gives you exactly that:

```{r }
dim(hospital) 

dim(hospital)[1] # first element : number of rows

dim(hospital)[2] # second element : number of columns

```

## Importing/exporting data 

Importing data into R is very important since statistics usually work with big datasets (introducing all values by hand would be a completely waste of time!). There are several ways, but the basic one is to use one of the built-in read and write functions: **read.table, write.table**, **read.csv, write.csv**...

```{r }
#change the working directory to your working directory !!!!
#setwd("~/Documents/IL3_DS_2023/LENGUAJE R I")

study <- read.csv("patients_data.csv") 
# don't forget the quotes when you write the path_to_your_file
study

study$difference <- study$temperature_1 - study$temperature_2 

write.csv(study, "new_patients_data.csv") 

```

We have stored the information in the csv (comma separated values) file called patients_data into a variable called study. Then I did some operation and wrote the result into a new csv file called new_patients_data.

Another way is to load data into Rstudio is to go the panel Environment --> Import Dataset. 


A tutotial about how to import data in R: https://www.datacamp.com/tutorial/r-data-import-tutorial
http://repo.darmajaya.ac.id/5012/1/R%20Programming%20for%20Bioinformatics.pdf

examples for import data from a URL: https://www.geos.ed.ac.uk/~weather/jcmb_ws/
Observe the repository! and download manually one file!!!

```{r}
#base R - import weather data
ad <- read.csv("https://www.geos.ed.ac.uk/~weather/jcmb_ws/JCMB_2006_Aug.csv")
head(ad)

#exercise:
#Try to repeat the example in: https://sceweb.sce.uhcl.edu/helm/WEBPAGE-R/my_files/DataInterface/Module-6/module6page.html
#Many websites provide data for consumption by its users. For example the World Health Organization(WHO) provides reports on health and medical information in the form of CSV, txt and XML files. Using R programs, we can programmatically extract specific data from such websites. Some packages in R which are used to scrap data form the web are − "RCurl",XML", and "stringr". They are used to connect to the URL’s, identify required links for the files and download them to the local environment.
```


```{r}
#Another options using two popular packages:

if (!require("data.table")) install.packages("data.table")

library(data.table)
ad <- fread("https://www.geos.ed.ac.uk/~weather/jcmb_ws/JCMB_2006_Aug.csv")
head(ad)
```

```{r}
#last one:readr

if (!require("readr")) install.packages("readr")
library(readr)
ad <- read_csv("https://www.geos.ed.ac.uk/~weather/jcmb_ws/JCMB_2006_Aug.csv")
head(ad)
```


Operadores:
R tiene una amplia gama de operadores para realizar diversas operaciones sobre objetos y estructuras de datos:
Operadores aritméticos:Suma, resta, multiplicación, división, etc.
Operadores lógicos:AND, OR, NOT, etc.
Operadores de comparación:Igualdad, desigualdad, mayor que, menor que, etc.
Operadores de asignación:Asignar un valor a una variable.
Operadores de extracción:Extraer elementos de vectores, matrices y data frames.
Control de flujo:R proporciona estructuras de control de flujo para controlar el flujo de ejecución de un programa:
Sentencias if-else:Ejecutar diferentes bloques de código dependiendo de una condición.
Bucles for:Repetir un bloque de código un número específico de veces.
Bucles while:Repetir un bloque de código mientras se cumpla una condición.
Funciones:
Las funciones son bloques de código reutilizables que realizan una tarea específica. Las funciones pueden tener 
argumentos de entrada y devolver un valor.
Gráficos:
R tiene una amplia gama de funciones para crear gráficos de alta calidad, incluyendo histogramas, diagramas de 
dispersión, gráficos de líneas, etc.



## Descriptive statistics

Descriptive statistics are numbers that summarize or describe your data. Some of the most common are listed below.

### Central tendency

```{r }
median(numbers)  # median
mean(numbers)    # mean 
```

### Dispersion

```{r }
range(numbers)     # returns a vector with the minimum and maximum of the given argument
var(numbers)      # variance 
sd(numbers)     # standard deviation
```

### Boxplot

A boxplot is a simple graphical summary of your data that helps comparisons between distributions. Figure.1 is a boxplot, you can see a thick black line that represents the median of your distribution (or the 2nd quantile or the 50th percentile), this means that 50% of your values fall below and the other 50% of your values fall above it. The limits of the blue box represent the 1st and 3rd quartile, meaning that 25% of your values will fall above the box and 25% below the box. In other words, you have 50% of your values between the range of the box and the limits of the box represent the interquartile range (IQR). The upper and lower whiskers lengths are 1.5 times the width of the IQR, but usually the width of a whisker captures the range of the data (upper whisker is the maximum and lower whisker is the minimum) like in Figure.1A. As you can see in Figure.1B some points spread out the whisker, these are called "outliers" of the distribution.


```{r ,fig.width=6, fig.height=4, fig.align="center", fig.cap="Boxplots", echo=FALSE}
op <- par(mfrow=c(1,2)) 
boxplot(study$temperature_2,col="blue", main="A")
a<-rnorm(20000,mean = 36.5)
boxplot(a,col="blue",main="B")
par(op)
```
###Dealing with missing values

One of the most important problem is deal with missing values (NA)

Create a medical data and explore it:

```{r, eval=T}
BMI <- 	data.frame(
  gender = c("Male", "Male","Female"), 
  height = c(NA, 171.5, 165), 
  weight = c(81,93, 78),
  Age = c(42,38,26))
print(BMI)
ls.str() #observe all memory objects
```

Some useful functions to deal with missing values


```{r, eval=T}
# There is missings?
is.na(BMI)
which(is.na(BMI), arr.ind = T) #missings by row and column
# Missings by col
colSums(is.na(BMI))

```


How to fix missing values?

```{r, eval=T}
# Data frame containing only complete observations
na.omit(BMI)


## Function fix permits to use the data editor (take care)
## -------------------------------------------
#fix(BMI)
#BMI
```


## Exercises

### Exercise 1

Now we will practice what we've just learned with simple problems.

Let's create a data frame manually. For that, we need to create a vector with each variable like the following code (you can copy paste the above code to the Rstudio interface):

```{r }
patients <- c("Watson", "Crick", "Darwin","Mendel", "Franklyn", "Curie", "Margulis","Lovelace")
temperature_1 <- c(39.3, 39, 39.4, 41, 38.5, 38.4, 40.1, 39.5)
temperature_2 <- c(37, 35.4, 37, 35, 36.4, 36.4, 37.3, 36.1)
age <- c(40,43,55,45,61,39,70,41)
gender <- c("M", "M", "M", "M", "F","F","F","F")
drug <- c("A", "B", "A", "B", "A", "B","A","B")
```

As you can see, we just have created a several vectors with data from patients. 

Now we can create a data frame:

```{r }
patients_data<-data.frame(patients=patients, temperature_1=temperature_1,
                          temperature_2=temperature_2, age=age, gender=gender,
                          drug=drug)
patients_data

#variable names
names(patients_data)
```

Now try to answer the questions below:

1. How many patients are in patients_data? 

```{r }
length(patients_data$patients)

dim(patients_data)[1]
```

2. How many males and females were in the study? 

```{r }
males <- patients_data$patients[patients_data$gender == "M"]
length(males)

# you don't need to create a new variable, but sometimes it's easier to read.
length(patients_data$patients[patients_data$gender == "F"])

```

3. How many patients were assigned to drug A or B? Try using the **table()** function.

```{r }
table(patients_data$drug)
```


4. What's the mean age of the patients? 
```{r }
mean(patients_data$age)

```

5. Print the number of patients having had a higher temperature of 39.5 before taking medication (temperature_1).

```{r }

high <- patients_data[patients_data$temperature_1 > 39.5,]
length(high$patients)

```

6. Use the function **boxplot()** to graphically see the distribution of temperature_1 (before medication) and temperature_2 (after medication). Then use the function **summary()** to print the summary statistics both temperatures.  

```{r }
boxplot(patients_data[,c("temperature_1","temperature_2")])

summary(patients_data[,c("temperature_1","temperature_2")])

```

### Exercise 2

Let's work with a bigger dataset. We have data that contains over 80.000 reports of UFO (Unidentified Flying Object) sightings and we are going to analyse some of the characteristics of those sightings.

Try to answer the questions below:

1. First of all, we should import the data. Download the dataset *ufo.csv* and import it to Rstudio so we can start working on it with the function **read.csv()**. You can modify the arguments of most functions. For example, to read the file properly you will need to change the character that separates the fields from the default "," to ";". That option is encoded in the argument **sep**.

```{r }
ufo <- read.csv("ufo.csv", sep = ";")

```

2. Use the function **names()** to know the names of the columns and see what kind of information do we have. 

```{r }
names(ufo)

```

3. What is the most common shape of UFO? Plot in a barplot the shapes and their counts.

```{r }
# we can get the counts with the function table()
counts <- table(ufo$shape)

# we can sort the counts and see that the most common shape is ligth
sort(counts)

# or as the table "counts" has names, we can get the name of the maximum value
names(counts)[counts == max(counts)]

# use the function barplot() to plot it
barplot(counts,las=2, col="green") 
# the las argument changes the direction of the labels of the y axis

```


4. What is the mean time of duration of UFO sightings in each country?

```{r }
# let's see which countries do we have
unique(ufo$country)

# calculate the mean for each country 
mean(ufo$duration.seconds.[ufo$country == "us"])
mean(ufo$duration.seconds.[ufo$country == "ca"])
mean(ufo$duration.seconds.[ufo$country == "au"])
mean(ufo$duration.seconds.[ufo$country == "gb"])

## If you want to do it in one command: use the function by()
# A data frame (ufo$duration.seconds.) is split into data frames subsetted 
# by the values of a factor (ufo$country), and function FUN (mean) 
# is applied to each subset in turn
by(data = ufo$duration.seconds.,INDICES = ufo$country, FUN = mean)


```


### Exercise 3 

We have been sent a dataset that contains information about 92 patients affected by a neuroendocrine tumour and in order to do a study we are going to analyse some of the characteristics of those patients.

Answer the questions below:

1. First of all, we should import the data in a correct format (numbers, date, characters, etc). Download the dataset **neurotum.csv** and import it to Rstudio so we can start working on it with the function **read.csv()**. You will need to change some of the arguments of the function **read.csv()**, like what is the character that separates the fields or the character that is used for decimal points (use *?read.csv* to look them up).   

```{r}
neurotum <- read.csv("neurotum.csv", sep=";", dec = ",")
str(neurotum)

```

2. Use the function **names()** to know the names of the columns and see what kind of information we have.
```{r}
names(neurotum)
```

3. Plot in a barplot the ECOG performance status and their counts. What is the most common ECOG performance status? 

```{r}
counts <- table(neurotum$ECOG.performance.status)
barplot(counts,col="blue")
## The most common ECOG performance status is 0 
```
4. What is the mean value of total bilirrubine in each sex (0 = male, 1 = female)? You should take into account that not all patients have measuraments, so some values are missing/Not Available (NA value). 

```{r}
mean(neurotum$Bilirubine..total..absolute.value[neurotum$Gender == 0], na.rm = T)

mean(neurotum$Bilirubine..total..absolute.value[neurotum$Gender == 1], na.rm = T)

```


see nice plots at <https://www.r-graph-gallery.com/>

5. Do a plot that relate gender and LDH

```{r, eval=FALSE}

library(ggplot2)
#library(hrbrthemes)

# A basic scatterplot with color depending on Species
ggplot(neurotum, aes(x=Bilirubine..total..absolute.value, y=LDH.absolute.value, color=as.factor(Gender))) + 
    geom_point(size=3) + labs(x = "Total bilirrubine (U)") + 
    labs(y = "LDH (U1)")



```


Now a little bit better:

```{r, eval=FALSE}
#better

#change values 0,1 of Gender by Male, Female in Sex:
neurotum$sex<- NA
neurotum[ rownames(neurotum[neurotum$Gender==0,]),"sex" ]<-"Male"
neurotum[ rownames(neurotum[neurotum$Gender==1,]),"sex" ]<-"Female"
# A basic scatterplot with color depending on Species
ggplot(neurotum, aes(x=Bilirubine..total..absolute.value, y=LDH.absolute.value, color=sex)) + 
    geom_point(size=3) + labs(x = "Total bilirrubine (U)") + 
    labs(y = "LDH (U1)")

```


### Exercise 4

From <https://rpubs.com/thanrajks/med-ana>


The biomedical data we are going to use is obtained from Kaggle website. The dataset contains information about diabetes of cohort of sample subjects. This dataset arises from a research study of the National Institute of Diabetes and Digestive and Kidney Diseases. The purpose of the dataset is to predict whether or not a patient has diabetes. It is based on certain test measurements included in the dataset. Here, the patients are all females at least 21 years old of Pima Indian heritage.

See kaggle in https://www.kaggle.com/

The datasets consists of several medical predictors/features and one target/response variable named as Outcome. We will first import the dataset into the workspace. Before that we have setup the Rstudio for carrying out the analysis. First, set the working directory using setwd(). Second, import the required library into the R Markdown file. It is shown here.

```{r}
#setwd("C:/Users/RajuPC/Documents/MyR/RajuBook")
#library(tidyverse) #Required for analysis, visualization
#library(plotly) # Required for interactive plotting of graphs
#library(ggsci) #Themes package for the plots
library(readr)
diab<-read_csv("diabetes.csv") # It reads the CSV file and assigns to diab object
#diabetes <- read.csv("~/Documents/IL3_DS_2023/LENGUAJE R I/diabetes.csv")
```

Data Exploration. The diab is a R data frame and we can see the data in many as follows:

```{r}
head(diab) # Elements of first few rows
tail(diab) # Elements of Last few rows
colnames(diab) #Names of Columns which are the names of predictors and outcome variables
str(diab) # Structure of the dataset
```

Descriptive statistics. Here using a summary() function one can easily obtain the descriptive statistics of the imported dataframe.

```{r}
summary(diab)
```
PROPOSED EXERCISES
It is proposed to carry out different simple analyses, tables and graphs to study these data and try to prepare a future model that predicts diabetes.




Try to follow in:  <https://rpubs.com/thanrajks/med-ana>

### More exercises

See more exercises at: <https://rviews.rstudio.com/categories/r-in-medicine/>

Some Thoughts on R / Medicine 2020

Analysing the HIV pandemic, Part 4: Classification of lab samples

Analysing the HIV pandemic, Part 3: Genetic diversity

Analysing the HIV pandemic, Part 2: Drug resistance testing

Analysing the HIV pandemic, Part 1: HIV in sub-Sahara Africa

R for Quantitative Health Sciences: An Interview with Jarrod Dalton

Statistics in Glaucoma: Part III

Statistics in Glaucoma: Part II

Statistics in Glaucoma: Part I <https://rviews.rstudio.com/2018/12/03/statistics-in-glaucoma-part-i/>


FINAL REMARK: MATERIAL USED IN UPF CLASSES, B. Dobon, S. Walsh, H. Laayouni,T.MONLEON 2018.