如何在 R 中使用条件变量构建 100 个投资组合?

问题描述

我是 R 的新手。我一直在尝试根据每个月的市值构建 100 个不同的投资组合。例如,对于 1957 年 3 月,我想构建 100 个投资组合。投资组合 1 将包含市值最小的股票。

head(Portfolios)
# A tibble: 6 x 7
# Groups:   Date [1]
  Date      permno    retx retadj.1mn    ME port.weight DateYear
  <yearmon> <fct>    <dbl>      <dbl> <dbl>       <dbl>    <dbl>
1 Mar 1957  15771  -0.103     -0.103  0.616       0.687     1957
2 Mar 1957  12351   0.586      0.586  1.15        0.725     1957
3 Mar 1957  22963  -0.167     -0.167  0.694       0.833     1957
4 Mar 1957  14461  -0.0638    -0.0638 1.42        1.52      1957
5 Mar 1957  16299   0          0      1.53        1.53      1957
6 Mar 1957  15739  -0.0625    -0.0625 1.46        1.55      1957

我尝试使用 cut() 函数,但没有用。我使用了以下代码

by(Portfolios,Portfolios$Date,function(x) cut_number(Portfolios$port.weight,100,label = c(1:100)))

但是没有用。如果我使用 ifelse() 会有 100 个条件,这似乎不对。我应该使用循环吗?谁能帮我?谢谢

编辑:我运行 dput(Portfolios) 并获得很长的结果,但结果的最后几行是:

2903148:2906727,2906728:2910307,2910308:2913893,2913894:2917481,2917482:2921078,2921079:2924672,2924673:2928278,2928279:2931886,2931887:2935496,2935497:2939121,2939122:2942767,2942768:2946429,2946430:2950102,2950103:2953783,2953784:2957487,2957488:2961198,2961199:2964905,2964906:2968624,2968625:2972352),ptype = integer(0),class = c("vctrs_list_of","vctrs_vctr","list"))),row.names = c(NA,-694L),class = c("tbl_df","tbl","data.frame"),.drop = TRUE),class = c("grouped_df","tbl_df","data.frame"))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)