Skip to content

Instantly share code, notes, and snippets.

@meaganewaller
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meaganewaller/600400bd207af973379d to your computer and use it in GitHub Desktop.
Save meaganewaller/600400bd207af973379d to your computer and use it in GitHub Desktop.
R Programming
x <- data.frame(x = 1:3, y = c(F, T, T))
#=> x y
# 1 1 FALSE
# 2 2 TRUE
# 3 3 TRUE
nrow(x)
#=> [1] 3
ncol(x)
#=> [1] 2
x <- factor(c("a", "b", "b", "a", "a", "b"))
#=> [1] a b b a a b
# Levels: a b
table(x)
#=> a b
# 3 3
unclass(x)
#=> [1] 1 2 2 1 1 2
# attr(,"levels")
# [1] "a" "b"
x <- factor(c("hello", "bye", "bye", "hello", "bye"), levels = c("hello", "bye"))
#=> [1] hello bye bye hello bye
# Levels: hello bye
x <- factor(c("hello", "bye", "bye", "hello", "bye"))
#=> [1] hello bye bye hello bye
# Levels: bye hello
x <- list(FALSE, "a", 5.5, 1)
#=> [[1]]
#[1] FALSE
#[[2]]
#[1] "a"
#[[3]]
#[1] 5.5
#[[4]]
#[1] 1
m <- matrix(nrow = 5, ncol = 4)
#=> [,1] [,2] [,3] [,4]
#[1,] NA NA NA NA
#[2,] NA NA NA NA
#[3,] NA NA NA NA
#[4,] NA NA NA NA
#[5,] NA NA NA NA
dim(m)
#=> [1] 5 4
m <- matrix(1:15, nrow = 5, ncol = 2)
#=> [,1] [,2]
#[1,] 1 6
#[2,] 2 7
#[3,] 3 8
#[4,] 4 9
#[5,] 5 10
m <- matrix(1:10, nrow = 5, ncol = 5)
#=> [,1] [,2] [,3] [,4] [,5]
#[1,] 1 6 1 6 1
#[2,] 2 7 2 7 2
#[3,] 3 8 3 8 3
#[4,] 4 9 4 9 4
#[5,] 5 10 5 10 5
m <- 1:15
dim(m) <- c(3, 5)
#=> [,1] [,2] [,3] [,4] [,5]
#[1,] 1 4 7 10 13
#[2,] 2 5 8 11 14
#[3,] 3 6 9 12 15
x <- 1:4
y <- 10:13
cbind(x, y)
#=> x y
#[1,] 1 10
#[2,] 2 11
#[3,] 3 12
#[4,] 4 13
rbind(x, y)
#=> [,1] [,2] [,3] [,4]
#x 1 2 3 4
#y 10 11 12 13
is.na(NA)
#=> [1] TRUE
is.nan(NA)
#=> [1] FALSE
is.nan(NaN)
#=> [1] TRUE
is.na(NaN)
#=> [1] TRUE
x <- c(1, NA, 10, 3)
is.na(x)
#=> [1] FALSE TRUE FALSE FALSE
is.nan(x)
#=> [1] FALSE FALSE FALSE FALSE
y <- c(NaN, NA, 0, 10)
is.na(y)
#=>[1] TRUE TRUE FALSE FALSE
is.nan(y)
#=>[1] TRUE FALSE FALSE FALSE
x <- 1:3
names(x)
#=> NULL
names(x) <- c("one", "two", "three")
#=> one two three
# 1 2 3
names(x)
#=> [1] "one" "two" "three"
x <- list(one = 1, two = 2, three = 3)
#$one
#[1] 1
#$two
#[1] 2
#$three
#[1] 3
m <- matrix(1:4, nrow = 2, ncol = 2)
dimnames(m) <- list(c("a", "b"), c("c", "d"))
#=> c d
# a 1 3
# b 2 4
x <- c(1,2)
#=> [1] 1 2
x <- c(TRUE, FALSE)
#=> [1] TRUE FALSE
x <- 1:10
#=> [1] 1 2 3 4 5 6 7 8 9 10
x <- c("hello", "world")
#=> [1] "hello" "world"
x <- vector("character", length = 5)
#=> [1] "" "" "" "" ""
x <- c(4, "a")
#=> [1] "4" "a"
x <- c(FALSE, 0)
#=> [1] 0 0
x <- c(TRUE, "t")
#=> [1] "TRUE" "t"
x <- 1:2
class(x)
#=> [1] "integer"
as.numeric(x)
#=> [1] 1 2
as.logical(x)
#=> [1] TRUE TRUE
as.character(x)
#=> [1] "1" "2"
x <- c("m", "e", "g")
as.numeric(x)
#=> [1] NA NA NA
#Warning message:
#NAs introduced by coercion
as.logical(x)
#=> [1] NA NA NA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment