r_programming Flashcards

1
Q

Write ifelse statement to print 0 if a > 0, else print TRUE, else print NA

A
  • ifelse(a > 0, TRUE, NA)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write ifelse state that replaces all NA values in the dataset “na_example” with ‘0’, otherwise keeps the current value

A
  • no_nas <- ifelse(is.na(na_example), 0, na_example)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

For the following vector, return TRUE if ANY of the values are TRUE:

  • z <- c(TRUE, TRUE, FALSE)
A
  • any(z)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

For the following vector, return TRUE only if ALL of the values are TRUE:

z <- c(TRUE, TRUE, FALSE)

A
  • all(z)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Create a function called “compute_s_n” that computes the sum of 1 to ‘n’, that accepts the parameter ‘n’

A

compute_s_n <- function(n) {

x <- 1:n

sum(x)

}

compute_s_n(100)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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.
A
  • new_names <- ifelse(nchar(murders$state)>8, murders$abb, murders$state)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

We will define a function sum_n for this exercise.

  1. 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.
  2. Use the function you just defined to determine the sum of integers from 1 to 5,000.
A
  1. # Create function called sum_n
    • sum_n <- function(x){
    • x <- 1:x
    • sum(x)
    • }
  2. # Use the function to determine the sum of integers from 1 to 5000
    • sum_n(5000)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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).

A

Create altman_plot
altman_plot <- function(x,y){
plot(x+y, y-x)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly