【问题标题】:Error using function in data.table in r在 r 中使用 data.table 中的函数时出错
【发布时间】:2017-10-18 22:39:39
【问题描述】:

我在 data.table 中使用了一个函数,由于某种原因,它在 data.table 中使用时不起作用,但在 R 环境中使用时效果很好。有人知道为什么会这样吗?

基本上,该函数将数组中最接近的年份分配给 data.table 中的给定年份。该函数需要一个变量是一年(在 data.table 中),第二个变量是可能年份的数组,其中要获得最接近的年份。代码示例如下。

我收到警告:

“警告信息: 在 YearsArray - YearI 中: 较长的对象长度不是较短对象长度的倍数"

library (data.table)

DAT<-data.table(Yr=1950:1960)
ArrayYearsB<- c(1950, 1955, 1960)

#---start---pair-years function----#
YearPairing <- function (YearI,YearsArray)
{
YearB=c(abs(YearsArray-YearI))
YearA=min(YearB)
YearA=grep(paste0("^",YearA,"$"),YearB)
YearA= YearsArray[YearA][1]
return(YearA)
}
#---end---pair-years function----#


DAT[,YearB:=YearPairing(Yr,ArrayYearsB)]

YearPairing(1950,ArrayYearsB)

【问题讨论】:

    标签: r function data.table


    【解决方案1】:

    对于这个特定的问题,您可以按如下方式使用 roll 参数。

    data.table(Yr=ArrayYearsB)[DAT, roll="nearest", .(Yr=i.Yr, that=x.Yr), on="Yr"]
          Yr that
     1: 1950 1950
     2: 1951 1950
     3: 1952 1950
     4: 1953 1955
     5: 1954 1955
     6: 1955 1955
     7: 1956 1955
     8: 1957 1955
     9: 1958 1960
    10: 1959 1960
    11: 1960 1960
    

    这里将向量转换为data.table,在DAT中添加所需的变量名称,然后在data.table中,DAT作为左连接使用on="Yr"。滚动参数被赋予“最近”,它选择向量的最近值。该结果被馈送到 j 语句,并使用 i.x. 提取所需的结果。

    分配回主表:

    DAT[, that := data.table(Yr = ArrayYearsB)[DAT, on=.(Yr), roll="nearest", x.Yr]]
    

    【讨论】:

    • 有没有办法将“that”作为列附加到 data.table DAT 中?
    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多