I have a function in R which returns a dataframe with 3 columns. Here is an example of an output from this function:
Vasicek(1)
Data DU Yield
1 2019-01-02 0.06027397 0.06428780
2 2019-01-02 0.16712329 0.06334294
3 2019-01-02 0.33698630 0.06336400
4 2019-01-02 0.69315068 0.06531485
5 2019-01-02 1.03013699 0.06833951
6 2019-01-02 1.38082192 0.07188101
7 2019-01-02 2.06849315 0.07848185
8 2019-01-02 2.75616438 0.08374200
9 2019-01-02 4.13424658 0.09019618
10 2019-01-02 5.51232877 0.09296135
However, when I call this function using sapply, it returns an object of the following class:
class(Vas)
[1] "matrix" "array"
I was not able to transform this matrix into a dataframe like the output of the function above.
Here is an example of an output of
Vas = sapply(1:3, Vasicek)
Vas
[,1] [,2] [,3]
Data Numeric,5 Numeric,5 Numeric,5
DU Numeric,5 Numeric,5 Numeric,5
Yield Numeric,5 Numeric,5 Numeric,5
and the code to obtain Vas
as it is
structure(list(structure(c(17898, 17898, 17898, 17898, 17898), class = "Date"),
c(1.38082191780822, 4.13424657534247, 0.167123287671233,
1.03013698630137, 2.06849315068493), c(0.0718810119824251,
0.0901961821101735, 0.0633429401279062, 0.0683395111286434,
0.0784818512451727), structure(c(17899, 17899, 17899, 17899,
17899), class = "Date"), c(2.06575342465753, 0.164383561643836,
0.0575342465753425, 2.75342465753425, 0.334246575342466),
c(0.0787273534815518, 0.063925820453163, 0.0641495440691283,
0.084047539923232, 0.0639744930251083), structure(c(17900,
17900, 17900, 17900, 17900), class = "Date"), c(2.75068493150685,
1.37534246575342, 1.02465753424658, 1.71232876712329, 0.161643835616438
), c(0.0820164309541394, 0.0726562058606185, 0.0700359442531045,
0.075140202621196, 0.0636353259162377)), .Dim = c(3L, 3L), .Dimnames = list(
c("Data", "DU", "Yield"), NULL))
Any suggestions on how to transform this output into a dataframe with 3 columns?
Consider using lapply
with bind_rows
. See the answer here: How to combine result of lapply to a data.frame?
library(dplyr)
Vas <- lapply(1:3, Vasicek) %>% bind_rows()