Introducción al curso

Este documento ofrece una guía práctica sobre la creación y manipulación de objetos básicos (vectores, matrices, listas y dataframes) en el lenguaje R. Exploraremos técnicas clave para trabajar eficientemente con estas estructuras, proporcionando ejemplos y pasos prácticos para su implementación. El objetivo es brindar una comprensión sólida y aplicable de estos conceptos esenciales en programación y análisis de datos en R.

Objetos de R

En R las variables son asignadas a R-Objects que en adelante llamaremos objetos.Los tipos de objetos que se pueden manejar en R incluyen:

  • Vectores
  • Listas
  • Arrays
  • Factores
  • Matrices
  • Dataframes
  • Cadenas

Vectores

Los vectores son arreglos de una sola dimensión y existen de seis tipos:

Comandos a utilizar

Algunos de los comandos que usaremos son:

Comando R
Concatenación c( )
Clase class( )
Tipo typeof( )

1. Vectores logicos: TRUE FALSE

Crear vector:

        a <- TRUE 
        class(a)
## [1] "logical"

Imprimir vector:

        print(a)
## [1] TRUE
    a
## [1] TRUE

2. Vectores numéricos

  numero <- 12.5
  print(numero)
## [1] 12.5
  numero
## [1] 12.5
  class(numero)
## [1] "numeric"
  typeof(numero)
## [1] "double"
  numeros <- c(12.5,25,32,43) #crear el objeto numeros
  print(numeros) #imprimir el objeto numeros
## [1] 12.5 25.0 32.0 43.0
  numeros #imprimir el objeto numeros
## [1] 12.5 25.0 32.0 43.0
  numeros[2:4] #subsetting
## [1] 25 32 43
  vec1 <- 1:25
  vec1
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  vec2 <- seq(from=1,to=10,by=0.5)
  vec2
##  [1]  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0  5.5  6.0  6.5  7.0  7.5  8.0
## [16]  8.5  9.0  9.5 10.0
  vec3 <- seq(10,102,5)
  vec3
##  [1]  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

Crear repeticiones de números

Crear secuencias de números repetidos 2 veces, intercalados

rep(1:4, 2)
## [1] 1 2 3 4 1 2 3 4

Crear secuencias de números repetidos 3 veces, sin intercalar

rep(1:4, each=3)
##  [1] 1 1 1 2 2 2 3 3 3 4 4 4

Crear secuencias de números repetidos, asignar número de repeticiones diferencial

rep(1:4, c(5,3,2,2))
##  [1] 1 1 1 1 1 2 2 2 3 3 4 4

Crear secuencias de números repetidos, repetir dos veces (each=2), longitud maxima de 4 (len=4)

rep(1:4, each = 2, len = 4) 
## [1] 1 1 2 2

Crear secuencias de números repetidos, repetir dos veces (each=2), repetir la secuncia generada 3 veces (times=3)

rep(1:4, each = 2, times = 3)
##  [1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4

3. Vectores enteros

        z <- 5L
        z
## [1] 5
    class(z)
## [1] "integer"

4. Vectores complejos

com<- 15+2i
typeof(com)
## [1] "complex"
com
## [1] 15+2i

5. Vectores caracter

        x <- "TRUE"
    x
## [1] "TRUE"
        print(class(x))
## [1] "character"
        y <- "7"
    y
## [1] "7"
        print(class(y))
## [1] "character"
        z <- "12+5"
    z
## [1] "12+5"
        print(class(z))
## [1] "character"
        z <- "manzana"
    z
## [1] "manzana"
        print(class(z))
## [1] "character"
alfabeto <- c(letters);alfabeto
##  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
## [20] "t" "u" "v" "w" "x" "y" "z"
alfabeto <- c(letters[1:5]);alfabeto
## [1] "a" "b" "c" "d" "e"

Crear repeticiones de un caracter

Crearemos un objeto A.rep que contenga 10 veces el caracter “A” y un objeto B.rep que contenga 10 veces el caracter “B” y posteriormente lo concatenamos en el objeto A.B

A.rep<-rep("A",10);A.rep
##  [1] "A" "A" "A" "A" "A" "A" "A" "A" "A" "A"
B.rep<-rep("B",10);B.rep
##  [1] "B" "B" "B" "B" "B" "B" "B" "B" "B" "B"
A.B<-c(A.rep,B.rep);A.B
##  [1] "A" "A" "A" "A" "A" "A" "A" "A" "A" "A" "B" "B" "B" "B" "B" "B" "B" "B" "B"
## [20] "B"

Ahora veremos como crearlo en un solo paso

A.B1<-c(rep("A",10),rep("B",10));A.B1
##  [1] "A" "A" "A" "A" "A" "A" "A" "A" "A" "A" "B" "B" "B" "B" "B" "B" "B" "B" "B"
## [20] "B"

6. Vectores RAW

        v <- charToRaw("Hello")
        print(class(v))
## [1] "raw"
        v
## [1] 48 65 6c 6c 6f

Vectores Fecha

Año-mes-día

e <- as.Date("2016-09-05");e
## [1] "2016-09-05"
f <- as.POSIXct("2018-04-05");e
## [1] "2016-09-05"

Convertir vectores

crear objeto numérico

var <- 5
class(var)
## [1] "numeric"
typeof(var)
## [1] "double"
var
## [1] 5

Convertir de número a carácter

var.c <- as.character(var)
class(var.c)
## [1] "character"
var.c
## [1] "5"

Entero a caracter

var_char2 <- as.character(2L)
var_char2
## [1] "2"
class(var_char2)
## [1] "character"
typeof(var_char2)
## [1] "character"

caracter a fecha

fecha <- "18-03-29"
class(fecha)
## [1] "character"
fecha <- as.Date(fecha)
class(fecha)
## [1] "Date"

Tarea 2.1 - RStudio - Vectores

Crear los siguientes vectores, imprimir e indicar su clase y tipo. Presentar los códigos de R utilizados.

  1. “Zacapa”
  2. 2022
  3. 24.3
  4. -12.5
  5. “22-3-4”
  6. as.Date(“22-3-4”)
  7. Imprima las letras 6, 11 y 15 del alfabeto
  8. Imprima las letras 5 a la 15 del alfabeto
  9. Convierta el los números c(3,6,45,50) en caracteres
  10. Converta los caracteres c(“1”,“2”,“3”,“4”,“5”) en números

Listas

Las listas difieren de los vectores en que pueden manejar varios tipos de objetos a la vez, inclusive listas en su interior.

Comandos a utilizar

Algunos de los comandos que usaremos son:

Comando R
Crear listas list()

Crear una lista

lista.1 <- list(5, "6", "USAC", "UMG", 24, list(c(2, 5, 3)), list(letters), list(c("USAC","UMG","UVG","UFM")))
lista.1
## [[1]]
## [1] 5
## 
## [[2]]
## [1] "6"
## 
## [[3]]
## [1] "USAC"
## 
## [[4]]
## [1] "UMG"
## 
## [[5]]
## [1] 24
## 
## [[6]]
## [[6]][[1]]
## [1] 2 5 3
## 
## 
## [[7]]
## [[7]][[1]]
##  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
## [20] "t" "u" "v" "w" "x" "y" "z"
## 
## 
## [[8]]
## [[8]][[1]]
## [1] "USAC" "UMG"  "UVG"  "UFM"

llamar objetos de la lista

lista.1[1] #llama al objeto 1 de lista.1 
## [[1]]
## [1] 5
lista.1[8] #llama al objeto 8 de lista.1
## [[1]]
## [[1]][[1]]
## [1] "USAC" "UMG"  "UVG"  "UFM"
lista.1[7] #llama al objeto 7 de lista.1
## [[1]]
## [[1]][[1]]
##  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
## [20] "t" "u" "v" "w" "x" "y" "z"

Matrices

Comandos a utilizar

Algunos de los comandos que usaremos son:

Comando R
Crear matriz matrix()
nombre filas rownames()
nombre columnas colnames()
nombres de las columnas names()

Las matrices son vectores 2D que se arreglan en filas y columnas.

Crear matriz de 35 y llenar por columnas*

matriz.1 <- matrix(c(1:15), nrow = 3, ncol = 5, byrow = FALSE)
class(matriz.1)
## [1] "matrix" "array"
matriz.1
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    4    7   10   13
## [2,]    2    5    8   11   14
## [3,]    3    6    9   12   15

Crear matriz de 35 y llenar por filas*

matriz.2 <- matrix(c(1:15), nrow = 3, ncol = 5, byrow = TRUE)
class(matriz.2)
## [1] "matrix" "array"
matriz.2
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    2    3    4    5
## [2,]    6    7    8    9   10
## [3,]   11   12   13   14   15

Asignar nombres a las filas y columnas de la matriz

colnames(matriz.1) <- c("A", "B", "C","D","E") 
rownames(matriz.1) <- c("a", "b", "c")
colnames(matriz.2) <- c("A", "B", "C","D","E") 
rownames(matriz.2) <- c("a", "b", "c")
matriz.1 
##   A B C  D  E
## a 1 4 7 10 13
## b 2 5 8 11 14
## c 3 6 9 12 15
matriz.2
##    A  B  C  D  E
## a  1  2  3  4  5
## b  6  7  8  9 10
## c 11 12 13 14 15

Llamar elementos de la matriz

matriz.1[1,] #llama a la fila 1
##  A  B  C  D  E 
##  1  4  7 10 13
matriz.1["a",] #llama a la fila 1
##  A  B  C  D  E 
##  1  4  7 10 13
matriz.1[,1] #llama a la columna 1
## a b c 
## 1 2 3
matriz.1[,"A"] #llama a la columna 1
## a b c 
## 1 2 3
matriz.1[1:2,] #llama a las fila 1 y 2
##   A B C  D  E
## a 1 4 7 10 13
## b 2 5 8 11 14
matriz.1[c("a","b"),] #llama a las fila 1 y 2
##   A B C  D  E
## a 1 4 7 10 13
## b 2 5 8 11 14
matriz.1[,c(1,3)] #llama a la columna 1 y 3
##   A C
## a 1 7
## b 2 8
## c 3 9
matriz.1[2,c(1,3)] #llama al vector de la fila 2 y las columnas 1 y 3
## A C 
## 2 8

Operaciones con matrices

matriz.1+matriz.2 #suma las dos matrices
##    A  B  C  D  E
## a  2  6 10 14 18
## b  8 12 16 20 24
## c 14 18 22 26 30
matriz.1*matriz.2 #multiplica las dos matrices
##    A  B   C   D   E
## a  1  8  21  40  65
## b 12 35  64  99 140
## c 33 72 117 168 225
matriz.1;matriz.2
##   A B C  D  E
## a 1 4 7 10 13
## b 2 5 8 11 14
## c 3 6 9 12 15
##    A  B  C  D  E
## a  1  2  3  4  5
## b  6  7  8  9 10
## c 11 12 13 14 15
matriz.1/matriz.2 #divide las dos matrices
##           A         B         C         D   E
## a 1.0000000 2.0000000 2.3333333 2.5000000 2.6
## b 0.3333333 0.7142857 1.0000000 1.2222222 1.4
## c 0.2727273 0.5000000 0.6923077 0.8571429 1.0

Tarea 2.2 - RStudio - Vectores

  1. ¿Cuál es la diferencia entre una lista y una matriz?
  2. Crea una lista que contenga los datos de 10 personas: nombres, apellidos, edad, profesion, nacionalidad, genero,

Dataframes

Los dataframes son objetos 2D que en sus columnas pueden contener diferentes clases de objetos

Comandos a utilizar

Algunos de los comandos que usaremos son:

Comando R
Crear dataframe as.data.frame()
Tipos de objetos str()
Convertir a factor as.factor()
Elaborar un boxplot plot()

crear un dataframe

lista_n <- list(list(1:3), list(4:6), list(7:9)) #crear una lista
df <- as.data.frame(lista_n) #convertir a dataframe

revise las diferencias entre una lista y un dataframe

lista_n;class(lista_n)
## [[1]]
## [[1]][[1]]
## [1] 1 2 3
## 
## 
## [[2]]
## [[2]][[1]]
## [1] 4 5 6
## 
## 
## [[3]]
## [[3]][[1]]
## [1] 7 8 9
## [1] "list"
df;class(df)
##   X1.3 X4.6 X7.9
## 1    1    4    7
## 2    2    5    8
## 3    3    6    9
## [1] "data.frame"

Crear un dataframe con nombre de columnas

lista_n <- list(list(nombre=c("Carlos", "Jose", "Mario")), list(peso=c(150,165,175)), list(edad=c(38,42,40)))#crear una lista y luego convertirla a dataframe
df <- as.data.frame(lista_n)
df2<-data.frame(nombre=c("Carlos", "Jose", "Mario"),peso=c(150,165,175),edad=c(38,42,40)) #crear el dataframe directamente
df2
##   nombre peso edad
## 1 Carlos  150   38
## 2   Jose  165   42
## 3  Mario  175   40

revisar como quedaron los nombres asignados

lista_n;class(lista_n)
## [[1]]
## [[1]]$nombre
## [1] "Carlos" "Jose"   "Mario" 
## 
## 
## [[2]]
## [[2]]$peso
## [1] 150 165 175
## 
## 
## [[3]]
## [[3]]$edad
## [1] 38 42 40
## [1] "list"
df;class(df)
##   nombre peso edad
## 1 Carlos  150   38
## 2   Jose  165   42
## 3  Mario  175   40
## [1] "data.frame"

Colocar nombres a la listas en dos pasos

En un primer paso se va a crear la lista y luego el dataframe

lista_n <- list(list(c("Carlos", "Jose", "Mario")), list(c(150,165,175)), list(c(38,42,40)));lista_n
## [[1]]
## [[1]][[1]]
## [1] "Carlos" "Jose"   "Mario" 
## 
## 
## [[2]]
## [[2]][[1]]
## [1] 150 165 175
## 
## 
## [[3]]
## [[3]][[1]]
## [1] 38 42 40
df<-as.data.frame(lista_n);df
##   c..Carlos....Jose....Mario.. c.150..165..175. c.38..42..40.
## 1                       Carlos              150            38
## 2                         Jose              165            42
## 3                        Mario              175            40

En el segundo paso vamos a crear un vector que contenga los nombres y luego los vamos a asignar a la lista utilizando el comando names y el símbolos <-

nombres<-c("Nombre", "Peso","Edad")
names(df)<-nombres
df
##   Nombre Peso Edad
## 1 Carlos  150   38
## 2   Jose  165   42
## 3  Mario  175   40
names(df)<-c("Name","Weigth","Age")
print(df)
##     Name Weigth Age
## 1 Carlos    150  38
## 2   Jose    165  42
## 3  Mario    175  40

concatenar la columna genero al dataframe df

df
##     Name Weigth Age
## 1 Carlos    150  38
## 2   Jose    165  42
## 3  Mario    175  40
df2<-as.data.frame(c(df,list(genero=c("H","H","H"))))
df2
##     Name Weigth Age genero
## 1 Carlos    150  38      H
## 2   Jose    165  42      H
## 3  Mario    175  40      H

crear un nuevo dataframe en un solo paso

df3<-as.data.frame(list(list(Name=c("Maria","Josefina")), list(Weigth=c(132,128)), list(Age=c(28,39)),list(genero=c("M","M"))))
df3
##       Name Weigth Age genero
## 1    Maria    132  28      M
## 2 Josefina    128  39      M

unir dos dataframes

df2.3<-rbind(df2,df3);df2.3
##       Name Weigth Age genero
## 1   Carlos    150  38      H
## 2     Jose    165  42      H
## 3    Mario    175  40      H
## 4    Maria    132  28      M
## 5 Josefina    128  39      M

Elaborar un boxplot de peso vs genero

df2.3
##       Name Weigth Age genero
## 1   Carlos    150  38      H
## 2     Jose    165  42      H
## 3    Mario    175  40      H
## 4    Maria    132  28      M
## 5 Josefina    128  39      M
str(df2.3) #revisar la estructura de los datos
## 'data.frame':    5 obs. of  4 variables:
##  $ Name  : chr  "Carlos" "Jose" "Mario" "Maria" ...
##  $ Weigth: num  150 165 175 132 128
##  $ Age   : num  38 42 40 28 39
##  $ genero: chr  "H" "H" "H" "M" ...
#plot(df2.3$Weigth~df2.3$genero) # va a generar un error

subsetting de un dataframe

df <- data.frame(id = 2:8, x = c(0, 5, 6, 8, 9, 15, -2), 
                  y = seq(2,14,2)) #crear un dataframe
names(df) #revisar los nombres de los envabezados
## [1] "id" "x"  "y"
str(df) #revisar la estructura del dataframe
## 'data.frame':    7 obs. of  3 variables:
##  $ id: int  2 3 4 5 6 7 8
##  $ x : num  0 5 6 8 9 15 -2
##  $ y : num  2 4 6 8 10 12 14

Ahora vamos a extraer los valores de los vectores dentro del dataframe

df$id #nos da los valores del objeto df y la columna id
## [1] 2 3 4 5 6 7 8
df[[1]] #realiza la misma operación
## [1] 2 3 4 5 6 7 8

En este paso vamos a crear un nuevo dataframe a partir de los vectores, a esto se le conoce como subsetting

df[1] #genera un nuevo dataframe con los valores de la primera columna
##   id
## 1  2
## 2  3
## 3  4
## 4  5
## 5  6
## 6  7
## 7  8
df["id"] #equivalente a la operación anterior
##   id
## 1  2
## 2  3
## 3  4
## 4  5
## 5  6
## 6  7
## 7  8
df[1:2] #genera un nuevo dataframe de las primeras dos columnas
##   id  x
## 1  2  0
## 2  3  5
## 3  4  6
## 4  5  8
## 5  6  9
## 6  7 15
## 7  8 -2
df[c("id", "x")] #equivalente a la operación anterior
##   id  x
## 1  2  0
## 2  3  5
## 3  4  6
## 4  5  8
## 5  6  9
## 6  7 15
## 7  8 -2

Tambien podemos utilizar operadores lógicos para hacer un subsetting

df[c(F,F,T)] #seleccionar columnas utilizando operadores lógicos
##    y
## 1  2
## 2  4
## 3  6
## 4  8
## 5 10
## 6 12
## 7 14

También podemos hacer un subsetting en formato de matriz

df[df$x > 4, c("id", "x", "y")]
##   id  x  y
## 2  3  5  4
## 3  4  6  6
## 4  5  8  8
## 5  6  9 10
## 6  7 15 12
df[df$x >= 5, c("id", "x", "y")] #nos da el mismo resultado
##   id  x  y
## 2  3  5  4
## 3  4  6  6
## 4  5  8  8
## 5  6  9 10
## 6  7 15 12
df[df$x >= 5, c("id", "y", "x")] #nos da el mismo resultado pero cambiamos el orden de las columnas
##   id  y  x
## 2  3  4  5
## 3  4  6  6
## 4  5  8  8
## 5  6 10  9
## 6  7 12 15

Filtrar dataframe

Podemos filtrar utilizando criterios, por ejemplo que la variable x sea mayor a 4

df[2:4, c("id", "y")]
##   id y
## 2  3 4
## 3  4 6
## 4  5 8

Convertir genero de caracter a factor y generar el boxplot El ejemplo anterior nos produjo un error, ya que la columna género no es un factor sino un caracter. Para que R genero el boxplot es necesario convertir la columna género de caracter a factor utilizando el comando as.factor

df2.3$genero<-as.factor(df2.3$genero)
str(df2.3)
## 'data.frame':    5 obs. of  4 variables:
##  $ Name  : chr  "Carlos" "Jose" "Mario" "Maria" ...
##  $ Weigth: num  150 165 175 132 128
##  $ Age   : num  38 42 40 28 39
##  $ genero: Factor w/ 2 levels "H","M": 1 1 1 2 2
plot(df2.3$Weigth~df2.3$genero) #va a generar un boxplot

plot(df2.3$Weigth~df2.3$genero,xlab="Género", ylab="Peso", col=3) #va a generar un boxplot

Cargar un dataframe desde una carpeta de archivos

R puede cargar diferentes tipos de archivos (ej. xlsx, xls, csv, tcv, bam, sam, fa, fasta, fastq, entre otros). Si nos han compartido un dataframe que viene en una hoja de excel, generlamente, recomiendo trabajarla como archivo de texto separado por comas (csv).

Para generar el archivo de texto (csv) desde excel, seguimos los siguientes pasos:

  1. Presionamos “Guardar como”
  2. En la pestaña de tipo de archivo le damos click al formato "CSV UTF-8 (comma delimited) (csv).
  3. Presionamos en “Guardar”

Es necesario que los encabezados del dataframe no contengan espacios ni caracteres especiales (ej. *, ¿, ´, %). Los espacios en los nombres de los encabezados se pueden substituir por puntos o barra baja.

Para el siguiente ejercicio, descargar la tabla starwars que se encuentra en https://drive.google.com/file/d/1MvwCxPpgwQY1VH1gJO6xPYEJZWGPFPDu/view?usp=sharing. Esta es una base de datos que pertenece a la biblioteca (dplyr), por el momento la usaremos como un archivo para practicar, ya que también se puede llamar directamente desde la biblioteca.

Una vez que descargues el archivo, abrelo con excel y luego con el block de notas y aprecia las diferencias.

#La ubicación en windows se realiza con doble backslash \\
#sep indica que el archivo está separado por comas
#header indica que la primera fila corresponde a los encabezados

df.n<-read.csv("E:\\windows\\Documents\\Cunzac\\Doctorado biomedicas\\Tablas\\starwars.csv", sep=",", header=T)

Exploremos los encabezados, luego las primeras 5 filas y las últimas 5 filas y las propiedades del dataframe

names(df.n)
##  [1] "name"       "height"     "mass"       "hair_color" "skin_color"
##  [6] "eye_color"  "birth_year" "sex"        "gender"     "homeworld" 
## [11] "species"    "films"      "vehicles"   "starships"
head(df.n,5)
##             name height mass hair_color  skin_color eye_color birth_year    sex
## 1 Luke Skywalker    172   77      blond        fair      blue       19.0   male
## 2          C-3PO    167   75       <NA>        gold    yellow      112.0   none
## 3          R2-D2     96   32       <NA> white, blue       red       33.0   none
## 4    Darth Vader    202  136       none       white    yellow       41.9   male
## 5    Leia Organa    150   49      brown       light     brown       19.0 female
##      gender homeworld species
## 1 masculine  Tatooine   Human
## 2 masculine  Tatooine   Droid
## 3 masculine     Naboo   Droid
## 4 masculine  Tatooine   Human
## 5  feminine  Alderaan   Human
##                                                                                                                                       films
## 1                                           A New Hope, The Empire Strikes Back, Return of the Jedi, Revenge of the Sith, The Force Awakens
## 2                    A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, Revenge of the Sith
## 3 A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, Revenge of the Sith, The Force Awakens
## 4                                                              A New Hope, The Empire Strikes Back, Return of the Jedi, Revenge of the Sith
## 5                                           A New Hope, The Empire Strikes Back, Return of the Jedi, Revenge of the Sith, The Force Awakens
##                             vehicles                starships
## 1 Snowspeeder, Imperial Speeder Bike X-wing, Imperial shuttle
## 2                                                            
## 3                                                            
## 4                                             TIE Advanced x1
## 5              Imperial Speeder Bike
tail(df.n,5)
##              name height mass hair_color skin_color eye_color birth_year    sex
## 83           Finn     NA   NA      black       dark      dark         NA   male
## 84            Rey     NA   NA      brown      light     hazel         NA female
## 85    Poe Dameron     NA   NA      brown      light     brown         NA   male
## 86            BB8     NA   NA       none       none     black         NA   none
## 87 Captain Phasma     NA   NA       none       none   unknown         NA female
##       gender homeworld species             films vehicles starships
## 83 masculine      <NA>   Human The Force Awakens                   
## 84  feminine      <NA>   Human The Force Awakens                   
## 85 masculine      <NA>   Human The Force Awakens             X-wing
## 86 masculine      <NA>   Droid The Force Awakens                   
## 87  feminine      <NA>   Human The Force Awakens
str(df.n)
## 'data.frame':    87 obs. of  14 variables:
##  $ name      : chr  "Luke Skywalker" "C-3PO" "R2-D2" "Darth Vader" ...
##  $ height    : int  172 167 96 202 150 178 165 97 183 182 ...
##  $ mass      : num  77 75 32 136 49 120 75 32 84 77 ...
##  $ hair_color: chr  "blond" NA NA "none" ...
##  $ skin_color: chr  "fair" "gold" "white, blue" "white" ...
##  $ eye_color : chr  "blue" "yellow" "red" "yellow" ...
##  $ birth_year: num  19 112 33 41.9 19 52 47 NA 24 57 ...
##  $ sex       : chr  "male" "none" "none" "male" ...
##  $ gender    : chr  "masculine" "masculine" "masculine" "masculine" ...
##  $ homeworld : chr  "Tatooine" "Tatooine" "Naboo" "Tatooine" ...
##  $ species   : chr  "Human" "Droid" "Droid" "Human" ...
##  $ films     : chr  "A New Hope, The Empire Strikes Back, Return of the Jedi, Revenge of the Sith, The Force Awakens" "A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, Revenge of the Sith" "A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, Revenge of t"| __truncated__ "A New Hope, The Empire Strikes Back, Return of the Jedi, Revenge of the Sith" ...
##  $ vehicles  : chr  "Snowspeeder, Imperial Speeder Bike" "" "" "" ...
##  $ starships : chr  "X-wing, Imperial shuttle" "" "" "TIE Advanced x1" ...
class(df.n)
## [1] "data.frame"

Cargar un dataframe desde una biblioteca

Para cargar un dataframe desde una biblioteca, primero es necesario instalar la biblioteca utilizando el comando install.packages(“nombre_bilbioteca”)

Luego debemos cargar la biblioteca a nuestro environmet utilizando el comando library(nombre_biblioteca)

install.packages(“dplyr”)

library(dplyr)

#install.packages("dplyr")
library(dplyr)
head(starwars,5)
## # A tibble: 5 × 14
##   name      height  mass hair_color skin_color eye_color birth_year sex   gender
##   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
## 1 Luke Sky…    172    77 blond      fair       blue            19   male  mascu…
## 2 C-3PO        167    75 <NA>       gold       yellow         112   none  mascu…
## 3 R2-D2         96    32 <NA>       white, bl… red             33   none  mascu…
## 4 Darth Va…    202   136 none       white      yellow          41.9 male  mascu…
## 5 Leia Org…    150    49 brown      light      brown           19   fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>

Vamos a guardar starwars dentro el objeto “st” para que se nos facilite utilizarla.

st<-starwars
st
## # A tibble: 87 × 14
##    name     height  mass hair_color skin_color eye_color birth_year sex   gender
##    <chr>     <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
##  1 Luke Sk…    172    77 blond      fair       blue            19   male  mascu…
##  2 C-3PO       167    75 <NA>       gold       yellow         112   none  mascu…
##  3 R2-D2        96    32 <NA>       white, bl… red             33   none  mascu…
##  4 Darth V…    202   136 none       white      yellow          41.9 male  mascu…
##  5 Leia Or…    150    49 brown      light      brown           19   fema… femin…
##  6 Owen La…    178   120 brown, gr… light      blue            52   male  mascu…
##  7 Beru Wh…    165    75 brown      light      blue            47   fema… femin…
##  8 R5-D4        97    32 <NA>       white, red red             NA   none  mascu…
##  9 Biggs D…    183    84 black      light      brown           24   male  mascu…
## 10 Obi-Wan…    182    77 auburn, w… fair       blue-gray       57   male  mascu…
## # ℹ 77 more rows
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>

Filtrar la base de datos starwars

Le vamos a decir que nos indique quienes tienen una estatura menor o igual a 150

head(st,5)
## # A tibble: 5 × 14
##   name      height  mass hair_color skin_color eye_color birth_year sex   gender
##   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
## 1 Luke Sky…    172    77 blond      fair       blue            19   male  mascu…
## 2 C-3PO        167    75 <NA>       gold       yellow         112   none  mascu…
## 3 R2-D2         96    32 <NA>       white, bl… red             33   none  mascu…
## 4 Darth Va…    202   136 none       white      yellow          41.9 male  mascu…
## 5 Leia Org…    150    49 brown      light      brown           19   fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>
st[st$height <= 150, "name"]
## # A tibble: 18 × 1
##    name                 
##    <chr>                
##  1 R2-D2                
##  2 Leia Organa          
##  3 R5-D4                
##  4 Yoda                 
##  5 Mon Mothma           
##  6 <NA>                 
##  7 Wicket Systri Warrick
##  8 Watto                
##  9 Sebulba              
## 10 Dud Bolt             
## 11 Gasgano              
## 12 Ratts Tyerell        
## 13 R4-P17               
## 14 <NA>                 
## 15 <NA>                 
## 16 <NA>                 
## 17 <NA>                 
## 18 <NA>

Realizar la misma función pero omitiendo las filas que contengan NA’s

na.omit(st[st$height <= 150, "name"])
## # A tibble: 12 × 1
##    name                 
##    <chr>                
##  1 R2-D2                
##  2 Leia Organa          
##  3 R5-D4                
##  4 Yoda                 
##  5 Mon Mothma           
##  6 Wicket Systri Warrick
##  7 Watto                
##  8 Sebulba              
##  9 Dud Bolt             
## 10 Gasgano              
## 11 Ratts Tyerell        
## 12 R4-P17

Filtrar con base a las filas 5 a la 15 e incluir las filas 62, 70 y 86

rownames(st)
##  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15"
## [16] "16" "17" "18" "19" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "30"
## [31] "31" "32" "33" "34" "35" "36" "37" "38" "39" "40" "41" "42" "43" "44" "45"
## [46] "46" "47" "48" "49" "50" "51" "52" "53" "54" "55" "56" "57" "58" "59" "60"
## [61] "61" "62" "63" "64" "65" "66" "67" "68" "69" "70" "71" "72" "73" "74" "75"
## [76] "76" "77" "78" "79" "80" "81" "82" "83" "84" "85" "86" "87"
rownames(st) %in% c(5:15,62,70,86)
##  [1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
## [13]  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [61] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE
## [73] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [85] FALSE  TRUE FALSE
st[rownames(st) %in% c(5:15,62,70,86),] #subsetting por filas
## # A tibble: 14 × 14
##    name     height  mass hair_color skin_color eye_color birth_year sex   gender
##    <chr>     <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
##  1 Leia Or…    150    49 brown      light      brown           19   fema… femin…
##  2 Owen La…    178   120 brown, gr… light      blue            52   male  mascu…
##  3 Beru Wh…    165    75 brown      light      blue            47   fema… femin…
##  4 R5-D4        97    32 <NA>       white, red red             NA   none  mascu…
##  5 Biggs D…    183    84 black      light      brown           24   male  mascu…
##  6 Obi-Wan…    182    77 auburn, w… fair       blue-gray       57   male  mascu…
##  7 Anakin …    188    84 blond      fair       blue            41.9 male  mascu…
##  8 Wilhuff…    180    NA auburn, g… fair       blue            64   male  mascu…
##  9 Chewbac…    228   112 brown      unknown    blue           200   male  mascu…
## 10 Han Solo    180    80 brown      fair       brown           29   male  mascu…
## 11 Greedo      173    74 <NA>       green      black           44   male  mascu…
## 12 Barriss…    166    50 black      yellow     blue            40   fema… femin…
## 13 Taun We     213    NA none       grey       black           NA   fema… femin…
## 14 Captain…     NA    NA unknown    unknown    unknown         NA   <NA>  <NA>  
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>
st[rownames(st) %in% c(5:15,62,70,86),"name"] #indica los nombre presentes solo en las filas indicadas
## # A tibble: 14 × 1
##    name              
##    <chr>             
##  1 Leia Organa       
##  2 Owen Lars         
##  3 Beru Whitesun lars
##  4 R5-D4             
##  5 Biggs Darklighter 
##  6 Obi-Wan Kenobi    
##  7 Anakin Skywalker  
##  8 Wilhuff Tarkin    
##  9 Chewbacca         
## 10 Han Solo          
## 11 Greedo            
## 12 Barriss Offee     
## 13 Taun We           
## 14 Captain Phasma

Guardaremos el subsetting en un objeto y luego en nuestro disco

st.1<-st[rownames(st) %in% c(5:15,62,70,86),] #subsetting por filas

st.1<- apply(st.1,2,as.character)#no siempre es necesario indicar esto

write.csv(st.1, "C:\\Users\\Manuel\\Documents\\Maestrias Investigacion\\st1.csv", row.names = FALSE, quote = FALSE)

Tarea 2.3

  1. Cree una lista que contenga los siguientes vectores: Nombre(Adrian, Jose, Eduardo, Maria, Ursula, Gloria), Edad(25,35,27,15,42,38), Genero(0,0,0,1,1,1), Profesion(Ag, Ag, QB, QB, Fo, Fo), Altura(165,168,171,170,150,161), Horas.semana(55,45,60,55,40,45).
  2. Despliegue la clase de la lista
  3. Imprima la lista
  4. Conviertala a un dataframe
  5. Convierta genero a factor
  6. Elabore un plot de genero vs altura, arregle las etiquetas de los ejes y coloque un color al boxplot
  7. Elabore un boxplot de profesion vs horas a la semana, arregle las etiquetas de los ejes y coloque un color al boxplot
  8. Elabore un subset del dataframe que contenga todos los campos por edad igual o mayor a 30