Section 3.6
x <- c(1, 2, -3, 4)
if(all(x>0)){
print("All Positives")
} else {
print("Not all positives")
}
## [1] "Not all positives"
FALSE when
at least one entry of a logical vector x is TRUE?x<-c(TRUE, FALSE, TRUE)
y<-c(TRUE, FALSE, FALSE)
z<-c(TRUE, TRUE, TRUE)
all(x)
## [1] FALSE
any(x)
## [1] TRUE
any(!x)
## [1] TRUE
all(!x)
## [1] FALSE
all(!y)
## [1] FALSE
all(!z)
## [1] FALSE
nchar tells you how many characters long
a character vector is. Write a line of code that assigns to the
object new_names the state abbreviation when the state name
is longer than 8 characters.library(dslabs)
data("murders")
longst<- function(j){
new_names<-ifelse(nchar(j)>8, murders$abb, murders$state)
}
pizza<-longst(murders$state)
pizza
## [1] "Alabama" "Alaska" "Arizona" "Arkansas" "CA" "Colorado"
## [7] "CT" "Delaware" "DC" "Florida" "Georgia" "Hawaii"
## [13] "Idaho" "Illinois" "Indiana" "Iowa" "Kansas" "Kentucky"
## [19] "LA" "Maine" "Maryland" "MA" "Michigan" "MN"
## [25] "MS" "Missouri" "Montana" "Nebraska" "Nevada" "NH"
## [31] "NJ" "NM" "New York" "NC" "ND" "Ohio"
## [37] "Oklahoma" "Oregon" "PA" "RI" "SC" "SD"
## [43] "TN" "Texas" "Utah" "Vermont" "Virginia" "WA"
## [49] "WV" "WI" "Wyoming"
sum_n that for any given value,
n , computes the sum of the integers from 1 to \(n\) (inclusive). Use the function to
determine the sum of integers from 1 to 5,000.sum_n<-function(n){
s<-seq(1, n, 1)
j<-sum(s)
return(j)
}
sum_n(5000)
## [1] 12502500
altman_plot that takes two
arguments, x and y, and plot the difference
against the sum.altman_plot<-function(x, y){
j<-plot(x-y, x+y)
return(j)
}
altman_plot(6, 1)
## NULL
x?x<-3
my_func<-function(y){
x<-5
y+5
}
x
## [1] 3
compute_s_n that for any given \(n\) computes the sum \(S_n=1^2+2^2+3^2+...+n^2\) Report the value
of the sum when \(n=10\).compute_s_n<-function(n){
love<-seq(1, n, 1)
pyar<-love^2
ishq<-sum(pyar)
return(ishq)
}
compute_s_n(10)
## [1] 385
s_n of size 25
using s_n <-vector("numeric", 25) and store in the
results of \(S_1, S_2, S_{25}\)m<-25
s_n<-vector("numeric", 25)
for(i in 1:m){
s_n[i]<-compute_s_n(i)
}
s_n
## [1] 1 5 14 30 55 91 140 204 285 385 506 650 819 1015 1240
## [16] 1496 1785 2109 2470 2870 3311 3795 4324 4900 5525
sapply.x<-1:25
s_n<-sapply(x, compute_s_n)
s_n
## [1] 1 5 14 30 55 91 140 204 285 385 506 650 819 1015 1240
## [16] 1496 1785 2109 2470 2870 3311 3795 4324 4900 5525
mapply.crab<-seq(1, 25, 1)
mapply(compute_s_n, crab)
## [1] 1 5 14 30 55 91 140 204 285 385 506 650 819 1015 1240
## [16] 1496 1785 2109 2470 2870 3311 3795 4324 4900 5525
n<-seq(1, 25, 1)
plot(n, s_n)
n<-seq(1,25, 1)
j<-n*(n+1)*(2*n+1)/6
identical(j, s_n)
## [1] TRUE