【问题标题】:Seq Function Erroring Out w/ Multiple Rows in RSeq 函数在 R 中出现多行错误
【发布时间】:2021-10-27 05:24:53
【问题描述】:

我正在尝试在一个函数中为我的数据集中的每一行生成序列行。我遇到的问题是seq 函数出错,因为我有多行。我已经包含了一个示例数据集和我的代码(序列调用是我函数底部的第三个)。

df<-data.frame(
  'Acct'=c("A","B","A"),
  'Rate'=c(8,8,12),
  'Amount'=c(1000,1000,1500),
  'Freq'=c(2,2,2),
  'MtM'=c(6,6,12),
  'YtM2'=c(.10,.10,.05),
  'periods'=c(12,12,24),
  'Price'=c(911.54,911.54,1050.37),
  'Date'=c('Sep 2021','Sep 2021', 'May 2021')
)

 dur <- function(Rate, periods,YtM2, Price ,MtM,Amount) {
  i <- 1:periods
  cf <- c(rep(Rate, periods - 1), Amount + Rate)
  pv <- (cf / (1 + YtM2) ^ i)
  weight<-pv/Price
  seqi<-seq(MtM/periods,MtM,length.out=periods)
  endResults<-sum(seqi*weight)
  return(seqi) 
  }
  
  dur(df$Rate,df$periods,df$YtM2,df$Price,df$MtM,df$Amount)

当我运行代码时出现错误:

Error in seq.default(MtM/periods, MtM, length.out = periods) : 
  'from' must be of length 1

理想情况下,我会暂时存储这些序列。我正在尝试使用dplyr::group_by 语句进行实验,其中我按AcctDate 分组,然后生成序列,即seqi&lt;-df%&gt;%group_by(Acct,Date)%&gt;%seq(MtM/df$periods,df$MtM, length.out=df$periods),但我只是收到此错误

Error in seq.default(., MtM/df$periods, df$MtM, length.out = df$periods) : 'from' must be of length 1 In addition: Warning message: In seq.default(., MtM/df$periods, df$MtM, length.out = df$periods) : first element used of 'length.out' argument

【问题讨论】:

    标签: r


    【解决方案1】:

    如果你想为每一行应用dur函数,你可以使用任何一个apply函数。

    例如,Map

    with(df, Map(dur, Rate, periods,YtM2, Price ,MtM,Amount))
    
    #[[1]]
    # [1] 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0
    
    #[[2]]
    # [1] 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0
    
    #[[3]]
    # [1]  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0  5.5  6.0  6.5
    #[14]  7.0  7.5  8.0  8.5  9.0  9.5 10.0 10.5 11.0 11.5 12.0
    

    我从函数中删除了最后一个 Price 参数,因为它重复了两次。

    【讨论】:

      【解决方案2】:

      我们可以使用 do.callMap 在按照 'dur' 中输入参数的顺序对列进行子集化

       do.call(Map, c(f = dur, unname(df[c(2, 7, 6, 8, 5, 3)])))
      [[1]]
       [1] 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0
      
      [[2]]
       [1] 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0
      
      [[3]]
       [1]  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0  5.5  6.0  6.5  7.0  7.5  8.0  8.5  9.0  9.5 10.0 10.5 11.0 11.5 12.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-23
        相关资源
        最近更新 更多