📊 R - Variables
Updated at 2017-10-13 17:51
# Assignment
# Variables are sometimes called R objects.
# Missing data is NA
x <- 42
# T and F are shorthands for TRUE and FALSE.
(T == TRUE)
(F == FALSE)
# List all active objects e.g. variables.
ls()
rm(x) # Remove an active object x.
rm(list=ls()) # Remove all active objects.
# Add or remove variables to search path.
# AVOID USING THESE AS THEY GENERATE HARD TO SPOT ERRORS.
attach(x)
detach(x)
# Dimensions of matrix x.
dim(x)
# Dimension names of matrix x.
dimnames(x)
# Length of vector x.
length(x)
Data type conversion is done with as.X()
.
# Casting
as.numeric(x)
as.factor(x)
as.matrix(x)
as.vector(x)
as.data.frame(x)
as.list(x)
as.character(x) # To string.
as.Date("20-Mar-13", "%d-%b-%y")
as.Date("2013-01-31", "%Y-%m-%d")
# Switch rows and columns.
t()
# Remove NAs from data frame.
na.omit(data)
Variable checks are done with is
.
is.factor(x)
is.matrix(x)
is.atomic(x) # Atomic vector.
is.list(x) # List vector.
is.vector(x) # Really should use (is.atomic() || is.list())
is.na(x)
is.data.frame(x)
All objects can have attributes. Most of them are removed on modification though.
y <- 1:10
attr(y, "description") <- "This is a vector"
attr(y, "description")
# [1] "This is a vector"
str(attributes(y))
# List of 1
# $ description: chr "This is a vector"
Sources
- Google Developers R Programming Videos
- Try R