set.seed(123) # Set seed for reproducibility
pets <- factor(sample(c("dog", "cat", "hamster", "goldfish"), 1000, replace = TRUE))
print(head(pets))
## [1] hamster hamster hamster cat     hamster cat    
## Levels: cat dog goldfish hamster
summary(pets)
##      cat      dog goldfish  hamster 
##      248      249      246      257

R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

# Initialize vector
triangular_numbers <- c()

# Calculate first 20 triangular numbers
for (n in 1:20) {
  triangular_numbers <- c(triangular_numbers, n * (n + 1) / 2)
}

# Name the elements of the vector with the first 20 letters of the alphabet
names(triangular_numbers) <- letters[1:20]
print(triangular_numbers)
##   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o   p   q   r   s   t 
##   1   3   6  10  15  21  28  36  45  55  66  78  91 105 120 136 153 171 190 210
# Select triangular numbers where the name is a vowel
vowels <- c("a", "e", "i", "o", "u")
vowel_triangular_numbers <- triangular_numbers[names(triangular_numbers) %in% vowels]
print(vowel_triangular_numbers)
##   a   e   i   o 
##   1  15  45 120

Irist Data Set

You can also embed plots, for example:

# Load the iris dataset
data(iris)

# Create a new data frame with numeric columns
iris_numeric <- iris[, sapply(iris, is.numeric)]
print(head(iris_numeric))
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1          5.1         3.5          1.4         0.2
## 2          4.9         3.0          1.4         0.2
## 3          4.7         3.2          1.3         0.2
## 4          4.6         3.1          1.5         0.2
## 5          5.0         3.6          1.4         0.2
## 6          5.4         3.9          1.7         0.4
# Calculate the means of its columns
iris_means <- colMeans(iris_numeric)
print(iris_means)
## Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
##     5.843333     3.057333     3.758000     1.199333

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.