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.
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:
Los vectores son arreglos de una sola dimensión y existen de seis tipos:
Algunos de los comandos que usaremos son:
| Comando | R |
|---|---|
| Concatenación | c( ) |
| Clase | class( ) |
| Tipo | typeof( ) |
Crear vector:
## [1] "logical"
Imprimir vector:
## [1] TRUE
## [1] TRUE
## [1] 12.5
## [1] 12.5
## [1] "numeric"
## [1] "double"
## [1] 12.5 25.0 32.0 43.0
## [1] 12.5 25.0 32.0 43.0
## [1] 25 32 43
## [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
## [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
## [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
## [1] 1 2 3 4 1 2 3 4
Crear secuencias de números repetidos 3 veces, sin intercalar
## [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
## [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)
## [1] 1 1 2 2
Crear secuencias de números repetidos, repetir dos veces (each=2), repetir la secuncia generada 3 veces (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
## [1] "TRUE"
## [1] "character"
## [1] "7"
## [1] "character"
## [1] "12+5"
## [1] "character"
## [1] "manzana"
## [1] "character"
## [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"
## [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
## [1] "A" "A" "A" "A" "A" "A" "A" "A" "A" "A"
## [1] "B" "B" "B" "B" "B" "B" "B" "B" "B" "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
## [1] "A" "A" "A" "A" "A" "A" "A" "A" "A" "A" "B" "B" "B" "B" "B" "B" "B" "B" "B"
## [20] "B"
Año-mes-día
## [1] "2016-09-05"
## [1] "2016-09-05"
crear objeto numérico
## [1] "numeric"
## [1] "double"
## [1] 5
Convertir de número a carácter
## [1] "character"
## [1] "5"
Entero a caracter
## [1] "2"
## [1] "character"
## [1] "character"
caracter a fecha
## [1] "character"
## [1] "Date"
Crear los siguientes vectores, imprimir e indicar su clase y tipo. Presentar los códigos de R utilizados.
Las listas difieren de los vectores en que pueden manejar varios tipos de objetos a la vez, inclusive listas en su interior.
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
## [[1]]
## [1] 5
## [[1]]
## [[1]][[1]]
## [1] "USAC" "UMG" "UVG" "UFM"
## [[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"
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*
## [1] "matrix" "array"
## [,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*
## [1] "matrix" "array"
## [,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
## 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
## A B C D E
## 1 4 7 10 13
## A B C D E
## 1 4 7 10 13
## a b c
## 1 2 3
## a b c
## 1 2 3
## A B C D E
## a 1 4 7 10 13
## b 2 5 8 11 14
## A B C D E
## a 1 4 7 10 13
## b 2 5 8 11 14
## A C
## a 1 7
## b 2 8
## c 3 9
## A C
## 2 8
Operaciones con matrices
## A B C D E
## a 2 6 10 14 18
## b 8 12 16 20 24
## c 14 18 22 26 30
## A B C D E
## a 1 8 21 40 65
## b 12 35 64 99 140
## c 33 72 117 168 225
## 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
## 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
Los dataframes son objetos 2D que en sus columnas pueden contener diferentes clases de objetos
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 dataframerevise las diferencias entre una lista y un dataframe
## [[1]]
## [[1]][[1]]
## [1] 1 2 3
##
##
## [[2]]
## [[2]][[1]]
## [1] 4 5 6
##
##
## [[3]]
## [[3]][[1]]
## [1] 7 8 9
## [1] "list"
## 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
## [[1]]
## [[1]]$nombre
## [1] "Carlos" "Jose" "Mario"
##
##
## [[2]]
## [[2]]$peso
## [1] 150 165 175
##
##
## [[3]]
## [[3]]$edad
## [1] 38 42 40
## [1] "list"
## 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
## 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 <-
## Nombre Peso Edad
## 1 Carlos 150 38
## 2 Jose 165 42
## 3 Mario 175 40
## Name Weigth Age
## 1 Carlos 150 38
## 2 Jose 165 42
## 3 Mario 175 40
concatenar la columna genero al dataframe df
## Name Weigth Age
## 1 Carlos 150 38
## 2 Jose 165 42
## 3 Mario 175 40
## 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
## 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
## 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
## '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" ...
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"
## '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
## [1] 2 3 4 5 6 7 8
## [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
## id
## 1 2
## 2 3
## 3 4
## 4 5
## 5 6
## 6 7
## 7 8
## id
## 1 2
## 2 3
## 3 4
## 4 5
## 5 6
## 6 7
## 7 8
## id x
## 1 2 0
## 2 3 5
## 3 4 6
## 4 5 8
## 5 6 9
## 6 7 15
## 7 8 -2
## 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
## 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
## id x y
## 2 3 5 4
## 3 4 6 6
## 4 5 8 8
## 5 6 9 10
## 6 7 15 12
## id x y
## 2 3 5 4
## 3 4 6 6
## 4 5 8 8
## 5 6 9 10
## 6 7 15 12
## 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
## 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
## '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
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:
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
## [1] "name" "height" "mass" "hair_color" "skin_color"
## [6] "eye_color" "birth_year" "sex" "gender" "homeworld"
## [11] "species" "films" "vehicles" "starships"
## 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
## 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
## '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" ...
## [1] "data.frame"
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)
## # 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.
## # 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
## # 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>
## # 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
## # 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
## [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"
## [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
## # 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