r_programming Flashcards
Write ifelse statement to print 0 if a > 0, else print TRUE, else print NA
- ifelse(a > 0, TRUE, NA)
Write ifelse state that replaces all NA values in the dataset “na_example” with ‘0’, otherwise keeps the current value
- no_nas <- ifelse(is.na(na_example), 0, na_example)
For the following vector, return TRUE if ANY of the values are TRUE:
- z <- c(TRUE, TRUE, FALSE)
- any(z)
For the following vector, return TRUE only if ALL of the values are TRUE:
z <- c(TRUE, TRUE, FALSE)
- all(z)
Create a function called “compute_s_n” that computes the sum of 1 to ‘n’, that accepts the parameter ‘n’
compute_s_n <- function(n) {
x <- 1:n
sum(x)
}
compute_s_n(100)
Use the ifelse function to write one line of code that assigns to the object “new_names” the state abbreviation when the state name is longer than 8 characters.
- So, for example, where the original vector has Massachusetts (13 characters), the new vector should have MA.
- But where the original vector has New York (8 characters), the new vector should have New York as well.
- new_names <- ifelse(nchar(murders$state)>8, murders$abb, murders$state)
We will define a function sum_n for this exercise.
- Create a function sum_n that for any given value, say n, creates the vector 1:n, and then computes the sum of the integers from 1 to n.
- Use the function you just defined to determine the sum of integers from 1 to 5,000.
- # Create function called
sum_n
- sum_n <- function(x){
- x <- 1:x
- sum(x)
- }
- # Use the function to determine the sum of integers from 1 to 5000
- sum_n(5000)
Create a function altman_plot that takes two arguments x and y and plots y-x (on the y-axis) against x+y (on the x-axis).
Create altman_plot
altman_plot <- function(x,y){
plot(x+y, y-x)
}