-
Notifications
You must be signed in to change notification settings - Fork 0
/
code-r.qmd
131 lines (111 loc) · 2.16 KB
/
code-r.qmd
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
```{r}
#| eval: false
## R Script Sample File
## Source: http://www.rexamples.com
## Basics
a <- 42
A <- a * 2 # R is case sensitive
print(a)
cat(A, "\n") # "84" is concatenated with "\n"
if(A > a) # true, 84 > 42
{
cat(A, ">", a, "\n")
}
## Functions
Square <- function(x) {
return(x ^ 2)
}
print(Square(4))
print(Square(x = 4)) # same thing
DoSomething(color = "red", number = 55)
## Countdown
countdown <- function(from)
{
print(from)
while(from != 0)
{
Sys.sleep(1)
from <- from - 1
print(from)
}
}
countdown(5)
## Reading user input
readinteger <- function()
{
n <- readline(prompt = "Enter an integer: ")
n <- as.integer(n)
if (is.na(n)) {
n <- readinteger()
}
return(n)
}
print(readinteger())
readinteger <- function() {
n <- readline(prompt = "Enter an integer: ")
if(!grepl("^[0-9]+$",n))
{
return(readinteger())
}
return(as.integer(n))
}
print(readinteger())
## Guess a random number game
readinteger <- function()
{
n <- readline(prompt = "Enter an integer: ")
if(!grepl("^[0-9]+$", n))
{
return(readinteger())
}
return(as.integer(n))
}
# real program start here
num <- round(runif(1) * 100, digits = 0)
guess <- -1
cat("Guess a number between 0 and 100.\n")
while(guess != num)
{
guess <- readinteger()
if (guess == num)
{
cat("Congratulations,", num, "is right.\n")
}
else if (guess < num)
{
cat("It's bigger!\n")
}
else if(guess > num)
{
cat("It's smaller!\n")
}
}
## Lists
sum(0:9)
append(LETTERS[1:13], letters[14:26])
c(1, 6, 4, 9) * 2
something <- c(1, 4, letters[2]) # indices start at one, you get (1,4,"b")
length(something)
## margrittr's pipe
diamonds %>%
filter(price > 1000) %>%
group_by(cut) %>%
tally() %>%
rename(tally = n) %>%
arrange(-tally) %>%
mutate(pct = tally / sum(tally)) -> df
## R native pipes (R > 4.1)
Sys.setenv("_R_USE_PIPEBIND_" = TRUE)
mtcars |> x => lm(mpg ~ cyl, data = x)
## ggplot2
plot = ggplot(diamonds, aes(x = price, y = carat)) +
geom_point(alpha = 0.3, colour = 'steelblue') +
labs(
title = "ggplot diamonds",
x = "Price, $",
y = "Carat"
) +
facet_wrap(~ cut) +
theme_minimal()
plot + coord_flip()
```