【问题标题】:Error taking the difference within a function在函数中取差时出错
【发布时间】:2021-10-22 04:58:12
【问题描述】:

下面的函数是我之前在fulldiam 是向量时能够使用的函数。

dN <- sapply(df,function(dn,fulldiam) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam))),fulldiam)

在此函数中,df 是数字数据帧(dim = 99 x 1399),fulldiam 是数字向量(长度 = 99)。

我正在尝试通过将fulldiam 向量更改为每个向量略有不同的位置来更改数据。所以现在我尝试使用 fulldiam_shifted 这是一个数字 data.frame (dim = 99 x 1399)。当我尝试使用更改运行该函数时,出现错误。

dN_shift <- sapply(df,function(dn,fulldiam_shifted) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam_shifted))),fulldiam_shifted)

Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] : 
  non-numeric argument to binary operator

我认为问题在于fulldiam_shifted 需要为df 的每一行调用每一列。有什么建议可以让这个功能发挥作用吗?

【问题讨论】:

    标签: r dataframe function vector difference


    【解决方案1】:

    我们可以在这里使用Map,因为两个数据集的维度相同

    Map(function(dn, fulldiam_new) 0.5*(head(dn,-1)+tail(dn,-1))*
                           abs(diff(log10(fulldiam_new))), df, fulldiam_shifted)
    

    【讨论】:

    • 谢谢akrun,这个答案解决了我的问题!
    猜你喜欢
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2013-11-05
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多