Skip to content

Instantly share code, notes, and snippets.

@aravindhebbali
Last active September 23, 2017 13:51
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 aravindhebbali/9a3814b9b4bb5c271d030b15ce4ecdf1 to your computer and use it in GitHub Desktop.
Save aravindhebbali/9a3814b9b4bb5c271d030b15ce4ecdf1 to your computer and use it in GitHub Desktop.
Code for Introduction to tibbles
# install library
install.packages('tibble')
library(tibble)
# create tibble
tibble(x = letters,
y = 1:26,
z = sample(100, 26))
# tibble features
# feature 1: tibble never changes input's type
(t <- tibble(x = letters, y = 1:26))
str(t)
# data frame
(d <- data.frame(x = letters[1:10], y = 1:10))
str(d)
# feature 2: tibble never adjusts variable names
# data frame
names(data.frame(`order value` = 10))
# tibble
names(tibble(`order value` = 10))
# feature 3: tibble never prints all rows
x <- 1:100
y <- letters[1]
tibble(x, y)
# feature 4: tibble never recycles a vector of length greater than 1
x <- 1:20
y <- c('a', 'b', 'c')
tibble(x, y)
# column names
tibble(
` ` = 'space',
`2` = 'integer',
`:)` = 'smiley'
)
# create tibbles using enframe
# vector of browser names
browser1 <- c('chrome', 'safari', 'firefox', 'edge')
# create tibble from browsers
enframe(browser1)
# named atomic vector
browser2 <- c(chrome = 40, firefox = 20, edge = 30, safari = 10)
# create tibble from browsers
enframe(browser2)
# tribble
tribble(
~x, ~y, ~z,
#--|--|----
1, TRUE, 'a',
2, FALSE, 'b'
)
# create tibble using `as_tibble()`
# data frame
as_tibble(iris)
# lists
l <- list(x = 1:32, y = sample(100, 32), z = replicate(32, letters, simplify = FALSE))
as_tibble(l)
# matrix
m <- matrix(sample(1000, 2600, replace = TRUE), ncol = 26)
colnames(m) <- letters
as_tibble(m)
# table
k <- table(mtcars$cyl)
as_tibble(k)
# tbl_df
k <- tbl_df(iris)
as_tibble(k)
```
# if an object is a tibble using `is_tibble()`
is_tibble(mtcars)
is_tibble(as_tibble(mtcars))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment