Data Summary
## ID Name Numeric Majority Sex
## Min. :1.00 Chandler:1 Min. :0.1757 Mode :logical Female:3
## 1st Qu.:2.25 Joey :1 1st Qu.:0.4820 FALSE:2 Male :3
## Median :3.50 Monica :1 Median :0.5884 TRUE :4
## Mean :3.50 Phoebe :1 Mean :0.5698
## 3rd Qu.:4.75 Rachel :1 3rd Qu.:0.6793
## Max. :6.00 Ross :1 Max. :0.9105
Class Identification for each column of the dataset:
class(data$ID)
## [1] "integer"
class(data$Name)
## [1] "factor"
class(data$Numeric)
## [1] "numeric"
class(data$Majority)
## [1] "logical"
class(data$Sex)
## [1] "factor"
Coerce character data type to integer data type:
x <- c("22", "27.0")
class(x)
## [1] "character"
y <- as.numeric(x)
class(y)
## [1] "numeric"
Coerce integer data type to logical data type:
example <- rnorm(10)
class(example)
## [1] "numeric"
a <- as.integer(example)
a > 0
## [1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
class(a)
## [1] "integer"
b <- as.logical(a)
class(b)
## [1] "logical"
Another example of coercing the integer data type to a logical data type:
vec1 <- 0:10
vec1
## [1] 0 1 2 3 4 5 6 7 8 9 10
class(vec1)
## [1] "integer"
vec2 <- as.logical(vec1)
vec2
## [1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
class(vec2)
## [1] "logical"
Coerce the character data type to an unordered factor data type:
description <- c("ok", "good", "better", "best", "better", "best", "best", "ok")
description
## [1] "ok" "good" "better" "best" "better" "best" "best" "ok"
class(description)
## [1] "character"
description <- factor(description, levels=c("ok", "good", "better", "best"))
description
## [1] ok good better best better best best ok
## Levels: ok good better best
class(description)
## [1] "factor"
This example shows the coercion of the character data type to an ordered factor type:
description <- c("ok", "good", "better", "best", "better", "best", "best", "ok")
description
## [1] "ok" "good" "better" "best" "better" "best" "best" "ok"
class(description)
## [1] "character"
description <- factor(description, levels=c("ok", "good", "better", "best"), ordered=TRUE)
description
## [1] ok good better best better best best ok
## Levels: ok < good < better < best
class(description)
## [1] "ordered" "factor"
Finally, here is an example of coercing an integer data type to a logical data type indicating even numbers are equal to true and odd numbers are equal to false:
vec3 <- 1:10
vec3
## [1] 1 2 3 4 5 6 7 8 9 10
class(vec3)
## [1] "integer"
vec3 <- as.logical(vec3%%2)
vec3%%2
## [1] 1 0 1 0 1 0 1 0 1 0
!(vec3%%2)
## [1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
class(vec3)
## [1] "logical"