'Yield curve sorting in R
I have a dataset from FedYieldCurve
data(FedYieldCurve)
which looks as follows but with more periods
R_3M R_6M R_1Y R_2Y R_3Y R_5Y R_7Y R_10Y
1981-12-31 12.92 13.90 14.32 14.57 14.64 14.65 14.67 14.59
1982-01-31 14.28 14.81 14.73 14.82 14.73 14.54 14.46 14.43
1982-02-28 13.31 13.83 13.95 14.19 14.13 13.98 13.93 13.86
1982-03-31 13.34 13.87 13.98 14.20 14.18 14.00 13.94 13.87
1982-04-30 12.71 13.13 13.34 13.78 13.77 13.75 13.74 13.62
1982-05-31 13.08 13.76 14.07 14.47 14.48 14.43 14.47 14.30
where I want to sort the dates by the types of yield curves (normal, inverse or humped).
The first question is how can I check for the curve types?
One possibility is to use sort but I really do not know what arguments to use here. Another way I could imagine is to use iterated if-functions, but this seems to be more difficult.
The second question after identifying the typ of the curve how can I sort them. Here I thought to use a for loop
for (i in 1:ncol(FedYieldCurve))
{
normal <- sort(FedYieldCurve)
inverse<- sort(FedYieldCurve)
humped<- (FedYieldCurve-normal-inverse)
list <- rbind(normal, inverse, humped)
}
Solution 1:[1]
First, create a data frame of differences diff by rows using apply. We have to transpose t() the result to get back data in a long format. Then get a vector of rows where all the diff are positive. These correspond to normal curves.
d_diff <- t(apply(FedYieldCurve, 1, diff)) #difference in yield by maturity
incr <- apply(d_diff, 1, function(x) all(x > 0, na.rm=TRUE)) #all increasing yield
decr <- apply(d_diff, 1, function(x) all(x < 0, na.rm=TRUE)) #all decreasing yield
normal <-FedYieldCurve[incr,]
inverse <-FedYieldCurve[decr,]
humped <-FedYieldCurve[!incr&!decr,]# not incr and not decr
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
