Instalación R: https://cran.r-project.org/
Instalación RStudio: https://www.rstudio.com/products/rstudio/download/
9 de julio de 2018
Instalación R: https://cran.r-project.org/
Instalación RStudio: https://www.rstudio.com/products/rstudio/download/
Directorio y variables que R está utilizando en este momento
getwd()
## [1] "C:/Users/Usuario/Documents/RESEARCH/2018/2018-R-HPC/material"
ls()
## character(0)
Asigne el valor 9 a la variable x, usando x <- 9. Observe nuevamente los objetos contenidos en el espacio de trabajo local.
x <- 9 ls()
## [1] "x"
Liste todos los archivos en el directorio de trabajo usando list.files() o dir().
list.files()
## [1] "1-Intro-CursoHPC.html" ## [2] "1-Intro-CursoHPC.Rmd" ## [3] "2-coneccion_clustser.html" ## [4] "2-coneccion_clustser.Rmd" ## [5] "2-coneccion_clustser.tex" ## [6] "Conceptos-figure" ## [7] "Conceptos-rpubs.html" ## [8] "Conceptos.md" ## [9] "Conceptos.Rpres" ## [10] "coneccion_clustser.html" ## [11] "coneccion_clustser.Rmd" ## [12] "doParallel.Rmd" ## [13] "hpc.png" ## [14] "HPC_for_dummies.pdf" ## [15] "hpc2.png" ## [16] "Imagen1.png" ## [17] "Imagen2.png" ## [18] "Imagen3.png" ## [19] "Imagen4.png" ## [20] "Imagen5.png" ## [21] "Imagen6.png" ## [22] "Imagen7.png" ## [23] "Imagen8.png" ## [24] "INTRODUCCION.Rmd" ## [25] "keygen-mac.png" ## [26] "maxresdefault.jpg" ## [27] "mytest3.R" ## [28] "operadores1.png" ## [29] "operadores2.png" ## [30] "Paralell-material.html" ## [31] "Paralell-material.Rmd" ## [32] "preuba.html" ## [33] "preuba.Rmd" ## [34] "pruebas.html" ## [35] "pruebas.Rmd" ## [36] "puttygen1.png" ## [37] "puttygen2.png" ## [38] "puttygen4.png" ## [39] "puttygen5.png" ## [40] "puttygen6.png" ## [41] "R_Basico.html" ## [42] "R_Basico.Rmd" ## [43] "R_Basico.tex" ## [44] "rocesamiento en paralelo en computador personal.Rmd" ## [45] "rocesamiento_en_paralelo_en_computador_personal.html" ## [46] "rocesamiento_en_paralelo_en_computador_personal.Rmd" ## [47] "rsconnect" ## [48] "Rstsudio.png" ## [49] "Rstudioserver.png" ## [50] "rstudioserver.Rmd" ## [51] "temario-hpc-cedia.html" ## [52] "temario-hpc-cedia.Rmd" ## [53] "useR2008hpcRexample.pdf" ## [54] "useR2010hpcTutorial.pdf"
dir()
## [1] "1-Intro-CursoHPC.html" ## [2] "1-Intro-CursoHPC.Rmd" ## [3] "2-coneccion_clustser.html" ## [4] "2-coneccion_clustser.Rmd" ## [5] "2-coneccion_clustser.tex" ## [6] "Conceptos-figure" ## [7] "Conceptos-rpubs.html" ## [8] "Conceptos.md" ## [9] "Conceptos.Rpres" ## [10] "coneccion_clustser.html" ## [11] "coneccion_clustser.Rmd" ## [12] "doParallel.Rmd" ## [13] "hpc.png" ## [14] "HPC_for_dummies.pdf" ## [15] "hpc2.png" ## [16] "Imagen1.png" ## [17] "Imagen2.png" ## [18] "Imagen3.png" ## [19] "Imagen4.png" ## [20] "Imagen5.png" ## [21] "Imagen6.png" ## [22] "Imagen7.png" ## [23] "Imagen8.png" ## [24] "INTRODUCCION.Rmd" ## [25] "keygen-mac.png" ## [26] "maxresdefault.jpg" ## [27] "mytest3.R" ## [28] "operadores1.png" ## [29] "operadores2.png" ## [30] "Paralell-material.html" ## [31] "Paralell-material.Rmd" ## [32] "preuba.html" ## [33] "preuba.Rmd" ## [34] "pruebas.html" ## [35] "pruebas.Rmd" ## [36] "puttygen1.png" ## [37] "puttygen2.png" ## [38] "puttygen4.png" ## [39] "puttygen5.png" ## [40] "puttygen6.png" ## [41] "R_Basico.html" ## [42] "R_Basico.Rmd" ## [43] "R_Basico.tex" ## [44] "rocesamiento en paralelo en computador personal.Rmd" ## [45] "rocesamiento_en_paralelo_en_computador_personal.html" ## [46] "rocesamiento_en_paralelo_en_computador_personal.Rmd" ## [47] "rsconnect" ## [48] "Rstsudio.png" ## [49] "Rstudioserver.png" ## [50] "rstudioserver.Rmd" ## [51] "temario-hpc-cedia.html" ## [52] "temario-hpc-cedia.Rmd" ## [53] "useR2008hpcRexample.pdf" ## [54] "useR2010hpcTutorial.pdf"
?list.files
Use la funcion args() con el nombre de una funcion list.files para conocer los argumentos de la funcion.
args(list.files)
## function (path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE, ## recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, ## no.. = FALSE) ## NULL
Use dir.create() para crear un directorio llamado "testdir" en el directorio de trabajo actual.
dir.create("testdir")
Configure "testdir"como nuevo directorio de trabajo.
setwd("testdir")
Cree un archivo en el directorio de trabajo llamado "mytest.R" usando la funcion file.create(). Este archivo será el único en el directorio creado. Revise esto listando todos los archivos del directorio de trabajo. Finalmente, revisa si "mytest.R" existe en el directorio de trabajo usando la funcion file exists().
setwd("C:/Users/Usuario/Documents/RESEARCH/2018/2018-R-HPC/material/testdir/")
file.create("mytest.R")
## [1] TRUE
list.files()
## [1] "mytest.R"
file.exists("mytest.R")
## [1] TRUE
Observa información sobre el archivo "mytest.R" usando file.info().
file.info("mytest.R")
## size isdir mode mtime ctime atime exe ## mytest.R NA NA <NA> <NA> <NA> <NA> <NA>
Cambie el nombre del archivo "mytest.R" a "mytest2.R" con file.rename().
file.rename("mytest.R", "mytest2.R")
## [1] FALSE
Haga una copia de "mytest2.R" a un nuevo archivo llamado "mytest3.R" usando file.copy().
file.copy("mytest2.R", "mytest3.R")
## [1] FALSE
Elimine mytest2.R usando
file.remove("mytest2.R")
## Warning in file.remove("mytest2.R"): no fue posible abrir el archivo
## 'mytest2.R', motivo 'No such file or directory'
## [1] FALSE
Borre el directorio 'testdir' con todo su contenido
setwd("C:/Users/Usuario/Documents/RESEARCH/2018/2018-R-HPC/material")
unlink("testdir", recursive = TRUE)
2+2
## [1] 4
2*2
## [1] 4
3**2
## [1] 9
2==3
## [1] FALSE
2!=3
## [1] TRUE
2<3
## [1] TRUE
x<- 1 y = 1 z<- "a" x+y
## [1] 2
my_numeric <- 42.5 my_character <- "some text" my_logical <- TRUE
class(my_numeric)
## [1] "numeric"
class(my_character)
## [1] "character"
class(my_logical)
## [1] "logical"
numeric_vector <- c(1, 10, 49)
character_vector <- c("a", "b", "c")
numeric_vector*10
## [1] 10 100 490
A_vector <- c(1, 2, 3) B_vector <- c(4, 5, 6) A_vector+B_vector
## [1] 5 7 9
A_vector == B_vector
## [1] FALSE FALSE FALSE
A_vector > B_vector
## [1] FALSE FALSE FALSE
seleccion <- A_vector > 2 seleccion
## [1] FALSE FALSE TRUE
A_vector[seleccion]
## [1] 3
Crear un vector x que contiene 20 valores aleatorios (a partir de una distribución normal) y 20 NAs.
x <- sample(c(rnorm(20), rep(NA, 20))) x
## [1] NA NA 0.31952159 NA -0.64726049 ## [6] NA 1.03751702 0.18725672 NA 1.59450867 ## [11] NA -0.93925487 -0.26555103 0.73674746 NA ## [16] NA NA 0.43064744 0.44604685 -0.18897738 ## [21] NA 0.29518888 0.71862611 NA NA ## [26] NA -0.44403756 NA 0.18321008 0.01636656 ## [31] NA NA -0.32786068 NA NA ## [36] NA 1.44465723 0.98161685 -1.54655333 NA
Obtener los primeros 10 elementos de x.
x[1:10]
## [1] NA NA 0.3195216 NA -0.6472605 NA ## [7] 1.0375170 0.1872567 NA 1.5945087
Extraer todos aquellos valores que no sean NA (missing data). Recuerde que is.na(x) es una función que arroja un vector con valores lógicos (TRUE y FALSE) de la misma longitud que x. TRUE corresponde para los valores NA y FALSE para los valores que no son NA.
x[is.na(x)]
## [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Si por el contrario lo que se quiere obtener es el vector con valores que no son NA, debe usarse el operador lógico de negación !, es decir !is.na(x) y que puede leerse como 'no es NA'.
y <- x[!is.na(x)] y
## [1] 0.31952159 -0.64726049 1.03751702 0.18725672 1.59450867 ## [6] -0.93925487 -0.26555103 0.73674746 0.43064744 0.44604685 ## [11] -0.18897738 0.29518888 0.71862611 -0.44403756 0.18321008 ## [16] 0.01636656 -0.32786068 1.44465723 0.98161685 -1.54655333
y > 0
## [1] TRUE FALSE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE ## [12] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE
y[y > 0]
## [1] 0.31952159 1.03751702 0.18725672 1.59450867 0.73674746 0.43064744 ## [7] 0.44604685 0.29518888 0.71862611 0.18321008 0.01636656 1.44465723 ## [13] 0.98161685
x[x > 0]
## [1] NA NA 0.31952159 NA NA 1.03751702 ## [7] 0.18725672 NA 1.59450867 NA 0.73674746 NA ## [13] NA NA 0.43064744 0.44604685 NA 0.29518888 ## [19] 0.71862611 NA NA NA NA 0.18321008 ## [25] 0.01636656 NA NA NA NA NA ## [31] 1.44465723 0.98161685 NA
x[!is.na(x) & x > 0]
## [1] 0.31952159 1.03751702 0.18725672 1.59450867 0.73674746 0.43064744 ## [7] 0.44604685 0.29518888 0.71862611 0.18321008 0.01636656 1.44465723 ## [13] 0.98161685
x[3]
## [1] 0.3195216
x[c(3, 5, 7)]
## [1] 0.3195216 -0.6472605 1.0375170
x[c(-2, -10)]
## [1] NA 0.31952159 NA -0.64726049 NA ## [6] 1.03751702 0.18725672 NA NA -0.93925487 ## [11] -0.26555103 0.73674746 NA NA NA ## [16] 0.43064744 0.44604685 -0.18897738 NA 0.29518888 ## [21] 0.71862611 NA NA NA -0.44403756 ## [26] NA 0.18321008 0.01636656 NA NA ## [31] -0.32786068 NA NA NA 1.44465723 ## [36] 0.98161685 -1.54655333 NA
x[-c(2, 10)]
## [1] NA 0.31952159 NA -0.64726049 NA ## [6] 1.03751702 0.18725672 NA NA -0.93925487 ## [11] -0.26555103 0.73674746 NA NA NA ## [16] 0.43064744 0.44604685 -0.18897738 NA 0.29518888 ## [21] 0.71862611 NA NA NA -0.44403756 ## [26] NA 0.18321008 0.01636656 NA NA ## [31] -0.32786068 NA NA NA 1.44465723 ## [36] 0.98161685 -1.54655333 NA
Cree un vector numérico con tres nombres de elementos usando vect <- c(foo = 11, bar = 2, norf = NA). Podemos observar el nombre de los elementos con la función names().
vect <- c(foo = 11, bar = 2, norf = NA) vect
## foo bar norf ## 11 2 NA
names(vect)
## [1] "foo" "bar" "norf"
Use la función names(), para cambiar los nombres de los vectores.
names(vect) <- c("m1", "m2", "m3")
vect
## m1 m2 m3 ## 11 2 NA
vect["m3"]
## m3 ## NA
my_matrix <- matrix(1:20, nrow=4, ncol=5) my_matrix
## [,1] [,2] [,3] [,4] [,5] ## [1,] 1 5 9 13 17 ## [2,] 2 6 10 14 18 ## [3,] 3 7 11 15 19 ## [4,] 4 8 12 16 20
dim(my_matrix)
## [1] 4 5
my_matrix[1,] #primera fila
## [1] 1 5 9 13 17
my_matrix[,1] #primera columna
## [1] 1 2 3 4
my_matrix[2,1] #celda de segunda final y primera columna
## [1] 2
paciente <- c("Bill", "Gina", "Kelly", "Sue")
my_data <- data.frame(paciente, my_matrix)
my_data
## paciente X1 X2 X3 X4 X5 ## 1 Bill 1 5 9 13 17 ## 2 Gina 2 6 10 14 18 ## 3 Kelly 3 7 11 15 19 ## 4 Sue 4 8 12 16 20
class(my_data)
## [1] "data.frame"
colnames(my_data)
## [1] "paciente" "X1" "X2" "X3" "X4" "X5"
cnames <- c("paciente", "edad", "peso", "test")
colnames(my_data) <- cnames
colnames(my_data)
## [1] "paciente" "edad" "peso" "test" NA NA
dim(cars)
## [1] 50 2
nrow(cars)
## [1] 50
ncol(cars)
## [1] 2
object.size(cars)
## 1576 bytes
names(cars)
## [1] "speed" "dist"
head(cars)
## speed dist ## 1 4 2 ## 2 4 10 ## 3 7 4 ## 4 7 22 ## 5 8 16 ## 6 9 10
tail(cars)
## speed dist ## 45 23 54 ## 46 24 70 ## 47 24 92 ## 48 24 93 ## 49 24 120 ## 50 25 85
summary(cars)
## speed dist ## Min. : 4.0 Min. : 2.00 ## 1st Qu.:12.0 1st Qu.: 26.00 ## Median :15.0 Median : 36.00 ## Mean :15.4 Mean : 42.98 ## 3rd Qu.:19.0 3rd Qu.: 56.00 ## Max. :25.0 Max. :120.00
str(cars)
## 'data.frame': 50 obs. of 2 variables: ## $ speed: num 4 4 7 7 8 9 10 10 10 11 ... ## $ dist : num 2 10 4 22 16 10 18 26 34 17 ...
cars[1, ]
## speed dist ## 1 4 2
cars[, 1]
## [1] 4 4 7 7 8 9 10 10 10 11 11 12 12 12 12 13 13 13 13 14 14 14 14 ## [24] 15 15 15 16 16 17 17 17 18 18 18 18 19 19 19 20 20 20 20 20 22 23 24 ## [47] 24 24 24 25
cars[, "speed"]
## [1] 4 4 7 7 8 9 10 10 10 11 11 12 12 12 12 13 13 13 13 14 14 14 14 ## [24] 15 15 15 16 16 17 17 17 18 18 18 18 19 19 19 20 20 20 20 20 22 23 24 ## [47] 24 24 24 25
cars$speed
## [1] 4 4 7 7 8 9 10 10 10 11 11 12 12 12 12 13 13 13 13 14 14 14 14 ## [24] 15 15 15 16 16 17 17 17 18 18 18 18 19 19 19 20 20 20 20 20 22 23 24 ## [47] 24 24 24 25
cars[c(1,10),]
## speed dist ## 1 4 2 ## 10 11 17
cars[cars$speed >20,]
## speed dist ## 44 22 66 ## 45 23 54 ## 46 24 70 ## 47 24 92 ## 48 24 93 ## 49 24 120 ## 50 25 85
cars[cars$speed == 20,]
## speed dist ## 39 20 32 ## 40 20 48 ## 41 20 52 ## 42 20 56 ## 43 20 64
newdata <- subset(cars, speed > 20, ) newdata
## speed dist ## 44 22 66 ## 45 23 54 ## 46 24 70 ## 47 24 92 ## 48 24 93 ## 49 24 120 ## 50 25 85
newdata <- subset(cars, speed >= 20, "speed") newdata
## speed ## 39 20 ## 40 20 ## 41 20 ## 42 20 ## 43 20 ## 44 22 ## 45 23 ## 46 24 ## 47 24 ## 48 24 ## 49 24 ## 50 25
my_vector <- 1:10 my_matrix <- matrix(1:9, ncol = 3) my_df <- mtcars[1:10,] my_list <- list(my_vector,my_matrix,my_df)
my_list[[1]]
## [1] 1 2 3 4 5 6 7 8 9 10
my_list[[2]]
## [,1] [,2] [,3] ## [1,] 1 4 7 ## [2,] 2 5 8 ## [3,] 3 6 9
my_list2 <- list(vector=my_vector,matrix=my_matrix,dataframe=my_df) my_list2[["vector"]]
## [1] 1 2 3 4 5 6 7 8 9 10
my_list2$vector
## [1] 1 2 3 4 5 6 7 8 9 10
plot(cars)
plot(x = cars$speed, y = cars$dist)
plot(x = cars$speed, y = cars$dist, xlab = "Speed", ylab = "Stopping Distance")
plot(cars, col = 2)
plot(cars, pch = 2)
boxplot(formula = mpg ~ cyl, data = mtcars)
hist(mtcars$mpg)
Basado en https://swcarpentry.github.io/r-novice-inflammation/02-func-R/
myfunction <- function(arg1, arg2, ... ){
statements
return(object)
}
Temperatura Fahrenheit a Kelvin
fahrenheit_to_kelvin <- function(temp_F) {
temp_K <- ((temp_F - 32) * (5 / 9)) + 273.15
return(temp_K)
}
# Punto de congelamiento del agua
fahrenheit_to_kelvin(32)
## [1] 273.15
# Punto de ebullición del agua fahrenheit_to_kelvin(212)
## [1] 373.15
Temperatura Kelvin a Celsius
kelvin_to_celsius <- function(temp_K) {
temp_C <- temp_K - 273.15
return(temp_C)
}
# Cero absolulto en Celsius
kelvin_to_celsius(0)
## [1] -273.15
Temperatura Fahrenheit a Celsius
fahrenheit_to_celsius <- function(temp_F) {
temp_K <- fahrenheit_to_kelvin(temp_F)
temp_C <- kelvin_to_celsius(temp_K)
return(temp_C)
}
# Punto de congelamiento del agua en Celsius
fahrenheit_to_celsius(32.0)
## [1] 0
Funciones anidadas
# Punto de congelamiento del agua en Celsius kelvin_to_celsius(fahrenheit_to_kelvin(32.0))
## [1] 0
for (i in 1:10) {
print(i)
}
## [1] 1 ## [1] 2 ## [1] 3 ## [1] 4 ## [1] 5 ## [1] 6 ## [1] 7 ## [1] 8 ## [1] 9 ## [1] 10
a <- 1:10 b <- 1:10 a+b
## [1] 2 4 6 8 10 12 14 16 18 20
res <- length(a)
for (i in seq_along(a)) {
res[i] <- a[i] + b[i]
}
res
## [1] 2 4 6 8 10 12 14 16 18 20
apply(cbind(a,b),1,sum)
## [1] 2 4 6 8 10 12 14 16 18 20
apply(cbind(a,b),1,mean)
## [1] 1 2 3 4 5 6 7 8 9 10
Cree una función que calcule la media (mean) de las columnas numéricas del data frame mtcars.
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb ## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 ## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 ## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 ## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 ## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 ## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Adapte la función anterior para que devuelva dos valores, la media (mean) y la mediana (median) de las columnas numéricas del data frame mtcars.