-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintro: R basics
118 lines (84 loc) · 2.38 KB
/
intro: R basics
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
#creating a sequence
print(seq(23,400))
#creating a prompt
?prompt
prompt="Input your name: "
print(prompt)
?run_console
#creating a dataframe
name <- c('John Doe','Peter Gynn','Jolie Hope')
age <- c(21, 23, 26)
data.frame<- c(name,age)
userage <-data.frame
#rounding a number
x <- 0.15 * 19.71
round(x,2)
?round
install.packages("dslabs")
library(dslabs)
install.packages("rtools")
#solving the quadratc formula
#2x^2 -x-4=0
a <- 2
b <- 1
c <- -4
solution_1 <- (-b - sqrt(b^2 - 4*a*c))/(2*a)
solution_2 <- (-b + sqrt(b^2 - 4*a*c))/(2*a)
print(solution_1)
print(solution_2)
#functions are nested
#functions are evaluated from the inside out when you nest them
# R functions are documented
#for variable names, stick to underscores and lower cases.
a <- 3
b <- 2
c <- -1
solution_1
solution_2
print(solution_1)
print(solution_2)
library(dslabs)
data("murders")
#checking the class of murders dataframe
class(murders)
#structure of murders dataframe
str(murders)
library(help = "stats")
#show the first six lines of murders dataframe
head(murders)
#show names of variables in murders dataframe
names(murders)
#show levels of the factors
levels(murders$region)
# == is a relational vector, it tests for equality
z <- 3 == 2
z
print(class(z))
#You can see the other relational operators by typing:
?Comparison
#turning something into an integer
as.integer()
# We extract the population like this:
p <- murders$population
# This is how we do the same with the square brackets:
o <- murders[["population"]]
# We can confirm these two are the same
identical(o, p)
# We can see the class of the region variable using class
class(murders$region)
# Determine the number of regions included in this variable using a nested funtion
length(levels(murders$region))
#The function table takes a vector as input and returns the frequency of each unique element in the vector.
# Write one line of code to show the number of states per region
table(murders$region)
#operation to find log base 4 of 1024
log(1024,4)
# The function reorder lets us change the order of the levels of a factor variable based on a summary computed on a numeric vector.
#create region dataframe
region <- murders$region
#create the value dataframe
value <- murders$total
#reorder the region data by the sum of total murders in "value", from least murders to most murders
region <- reorder(region, value, FUN = sum)
levels(region)
?reorder