Print examples of chapter 19 of 'R for Dummies'.

Description

To print a listing of all examples of a chapter, use ch19(). To run all the examples of ch19(), use example(ch19).

Usage

1
ch19()

See Also

toc

Other Chapters: ch01, ch02, ch03, ch04, ch05, ch06, ch07, ch08, ch09, ch10, ch11, ch12, ch13, ch14, ch15, ch16, ch17, ch18, ch20

Examples

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
# Chapter 19 - Ten Things You Can Do in R That You Would've Done in Microsoft Excel

# Adding Row and Column Totals

iris.num <- iris[, -5]

colSums(iris.num)
colMeans(iris.num)

apply(iris.num, 2, min)
apply(iris.num, 2, max)

sapply(iris.num, min)
sapply(iris.num, max)


# Formatting Numbers

format(12345.6789, digits=9, decimal.mark=",",
   big.mark=" ",small.mark=".", , small.interval=3)

x <- colMeans(mtcars[, 1:4])
format(x, digits=2, nsmall=2)

x <- seq(0.5, 0.55, 0.01)
sprintf("%.1f %%", 100*x)

set.seed(1)
x <- 1000*runif(5)
sprintf("$ %3.2f", x)

stuff <- c("bread", "cookies")
price <- c(2.1, 4)
sprintf("%s costed $ %3.2f ", stuff, price)


# Sorting Data

with(mtcars, mtcars[order(hp), ])
with(mtcars, mtcars[order(hp, decreasing=TRUE), ])

# Making Choices with If

mtcars <- within(mtcars,
   mpgClass <- ifelse(mpg < mean(mpg), "Low", "High"))

mtcars[mtcars$mpgClass == "High", ]


# Calculating Conditional Totals

with(mtcars, mean(mpg))
with(mtcars, mean(mpg[hp < 150]))
with(mtcars, mean(mpg[hp >= 150]))
with(mtcars, length(mpg[hp > 150]))


# Transposing Columns or Rows

x <- matrix(1:12, ncol=3)
x
t(x)

t(mtcars[1:4, ])


# Finding Unique or Duplicated Values

unique(mtcars$cyl)
dupes <- duplicated(iris)
head(dupes)
which(dupes)
iris[dupes, ]
iris[!dupes, ]
nrow(iris[!dupes, ])


# Working with Lookup Tables

index <- match("Toyota Corolla", rownames(mtcars))
index
mtcars[index, 1:4]


# Working with Pivot Tables

with(mtcars, tapply(hp, list(cyl, gear), mean))
aggregate(hp~cyl+gear+am, mtcars, mean)


# Using the Goal Seek and Solver

sales <- function(price) { 100 - 0.5 * price }
revenue <- function(price) { price * sales(price) }


par(mfrow=c(1, 2))
curve(sales, from=50, to=150, xname="price", ylab="Sales", main="Sales")
curve(revenue, from=50, to=150, xname="price", ylab="Revenue", main="Revenue")
par(mfrow=c(1, 1))

optimize(revenue, interval=c(50, 150), maximum=TRUE)