Data Types

Numeric

x = 12.2 # 
x
## [1] 12.2
class(x)
## [1] "numeric"
Incluso si el valor asignado es un entero, este se guarda como un valor numérico
k = 12
k
## [1] 12
class(k)
## [1] "numeric"
Se puede comprobar
is.integer(k)
## [1] FALSE
is.integer(x)
## [1] FALSE
is.integer(3)
## [1] FALSE

Integer

y = as.integer(12)
y
## [1] 12
class(y)
## [1] "integer"
is.integer(y)
## [1] TRUE
Obligado
as.integer(12.6)
## [1] 12
as.integer("12.6")
## [1] 12
as.integer("Claudio")
## Warning: NAs introduced by coercion
## [1] NA
Valores lógicos
as.integer(TRUE)
## [1] 1
as.integer(FALSE)
## [1] 0

Complejos

z = 1 + 2i
z
## [1] 1+2i
class(z)
## [1] "complex"
sqrt(-1)
## Warning in sqrt(-1): NaNs produced
## [1] NaN
sqrt(-1+0i)
## [1] 0+1i
sqrt(as.complex(-1))
## [1] 0+1i
as.complex(-1)
## [1] -1+0i

Logical

x = 1; y= 2
x
## [1] 1
y
## [1] 2
z = x > y
z
## [1] FALSE
class(z)
## [1] "logical"
Operaciones básicas ‘&’, “l”, “!”
v= TRUE ; f = FALSE
v & f
## [1] FALSE
v | f
## [1] TRUE
!v
## [1] FALSE

Character

x= as.character(12.6)
x
## [1] "12.6"
class(x)
## [1] "character"
nombre= "Juan" ; apellido= "Pérez"
paste(nombre, apellido)
## [1] "Juan Pérez"
sprintf("%s tiene %d quetzales", "Juan", 100)
## [1] "Juan tiene 100 quetzales"
nombre= "Pedro"
cantidad= 100
sprintf("%s tiene %d quetzales", nombre, cantidad)
## [1] "Pedro tiene 100 quetzales"
nombre= "Juan"
sprintf("%s no %s dinero", nombre, "tiene")
## [1] "Juan no tiene dinero"

VECTOR

numeric
c(2,3,5)
## [1] 2 3 5
logical
c(TRUE, FALSE, TRUE, FALSE, FALSE)
## [1]  TRUE FALSE  TRUE FALSE FALSE
character
c("a", "b", "c")
## [1] "a" "b" "c"
length(c(1:5))
## [1] 5
length(c("a", "b", "c"))
## [1] 3

Combinando vectores

n = c(2,3,5)
s= c('aa', 'bb', 'cc', 'dd', 'ee')
c(n,s)
## [1] "2"  "3"  "5"  "aa" "bb" "cc" "dd" "ee"
a = c(1:3)
b = c(4:6)
c(a,b)
## [1] 1 2 3 4 5 6
b = c('4','5','6')
c(a,b)
## [1] "1" "2" "3" "4" "5" "6"

Aritmética con vectores

a = c(1,3,5,7)
b = c(1,2,4,8)

2* a
## [1]  2  6 10 14
a + b
## [1]  2  5  9 15
a - b
## [1]  0  1  1 -1
a * b
## [1]  1  6 20 56
a / b
## [1] 1.000 1.500 1.250 0.875
# Recycling rule
u = c(10,20,30)
v = c(1:9)
u
## [1] 10 20 30
v
## [1] 1 2 3 4 5 6 7 8 9
u + v
## [1] 11 22 33 14 25 36 17 28 39
# Index
s = c('a','b','c','d','e')
s
## [1] "a" "b" "c" "d" "e"
s[2]
## [1] "b"
# Numeric index
s[c(2:4)]
## [1] "b" "c" "d"
s[c(1,3)]
## [1] "a" "c"
# Logical index

s = c('a','b','c','d','e')
s
## [1] "a" "b" "c" "d" "e"
L = c(FALSE, TRUE, FALSE, TRUE, FALSE)

s[L]
## [1] "b" "d"