0

In one of my homework, I am asked to print the prices of a bond over 2015,2016,2017,2018. Since 2015,2016 have 252 trading days, 2017 with 251 and 2018 with 250, I need to write an if statement. Here is my attempt:

plt <- function(a) {
  if (a == 2015) {
    x <- 1:252
  }
  else if (a == 2016) {
    x <- 1:252
  }
  else if (a == 2017) {
    x <- 1:251
  } else {
    x <- 1:250
  }
  plot(x=x, y=data[data$Year == a, 5], type="l", col="red")
}

However,when I input

function(c(2015, 2016, 2017, 2018))

only draft of 2015 shows up and R returns

Warning messages:
1: In if (a == 2015) { :
  the condition has length > 1 and only the first element will be used
2: In data$Year == a :
  longer object length is not a multiple of shorter object length  

If I input these years seperately, it gives four perfect plots.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Alexis
  • 1
  • 2
  • Do you have the date associated with each price? If so, I think that printing those would be better. If not, then what you probably want to visualize is the distributions of the prices (by year), in which case a scatterplot is less suited to the task than other options like boxplot, histogram, or frequency polygon. – mgiormenti Mar 31 '19 at 00:10
  • 2
    Your `if` statement works fine, but it only runs on the first element. Put it in a `for` loop, `for (i in 1:length(a)) { ...your code with a[i] instead of a...}`. – Gregor Thomas Mar 31 '19 at 00:29
  • Could you provide some information on the object called `data` please? – NM_ Mar 31 '19 at 00:50
  • This is a bit confusing, but it's great that you have provided some code. First I wonder if instead of `function(c(2015,2016,2017,2018)` you mean `plt(2015,2016,2017,2018)`. Instead of `if` you probably want `ifelse` which will use a vectorized approach. – Elin Mar 31 '19 at 07:19
  • Thank you guys. The problem is not fixed. – Alexis Mar 31 '19 at 17:13

1 Answers1

0

Let's assume that instead of function(c(2015,2016,2017,2018)you mean plt(c(2015,2016,2017,2018). If I'm wrong on that I'll delete the answer.

Let's start the function. In this case, a == c(2015, 2016, 2017, 2018).

In your function you ask, does a == 2015. No it does not; a is a vector of length 4 as shown above. 2015 in r is a scalar or a vector of length 1.

Does a == 2016? No and likewise for 2017 and 2018. So none of your if conditions are ever true and hence your plot() can't work because x is never created.

Instead you might want to rewrite your code to take a and work on each element. Also you might want to simplify by creating a_length <- c(252, 252, 251, 205)rather than writing everything out.

At that point you can use a for loop or lapply() to get the plots.

Elin
  • 6,507
  • 3
  • 25
  • 47