【问题标题】:R add columns by loop in data tableR在数据表中循环添加列
【发布时间】:2015-02-03 22:00:31
【问题描述】:

我有一个这样的数据表:

DT <- data.table(ID=rep(c(1:2),each=6), year=rep(c(2003:2006),each=3), month=rep(c(5:8),3), day=rep(c(11:14),3),value=c(101:112))

我想添加具有条件的列:

1、添加5列名称:V100、V102、V105、V108、V112

2、在每一列中,按ID和年份分组,对小于列名中的值的值求和,例如:对于V112列,对小于112的值求和

所以结果会是这样的:

DT1 <- data.table(ID=rep(c(1:2),each=2), year=c(2003:2006), "100"=rep(0,4), "102"=c(2,0,0,0),"105"=c(3,2,0,0),"108"=c(3,3,2,0),"112"=rep(3,4))

我尝试编写代码但无法弄清楚:

degree <- c(100,102,105,108,112)    
 for (d in degree)
{  
   f_year <- function(d) {sum(DT$value <= d)}
   DT <- DT[,d:=f_year(),by=list(ID,year)]
}

任何帮助将不胜感激!

【问题讨论】:

    标签: r for-loop data.table


    【解决方案1】:

    这就是lapply 的用途。

    degree <- c(100, 102, 105, 108, 112)  
    myfun <- function(x,y) sum(y <= x)
    DT1 <- DT[, lapply(degree, myfun, value), by = .(ID, year)]
    setnames(DT1, c("ID", "year", as.character(degree)))
    

    结果:

    > DT1
       ID year 100 102 105 108 112
    1:  1 2003   0   2   3   3   3
    2:  1 2004   0   0   2   3   3
    3:  2 2005   0   0   0   2   3
    4:  2 2006   0   0   0   0   3
    

    【讨论】:

    • 您是在输入参数之间吗?现在好点了吗?
    • @Floo0,我倾向于忽略这些无用的 cmets。
    【解决方案2】:

    只是另一种方式:

    cols = c(100,102,105,108,112)
    DT[, lapply(cols, function(x) sum(value <= x)), by=.(ID, year)]
    #    ID year V1 V2 V3 V4 V5
    # 1:  1 2003  0  2  3  3  3
    # 2:  1 2004  0  0  2  3  3
    # 3:  2 2005  0  0  0  2  3
    # 4:  2 2006  0  0  0  0  3
    

    然后你就可以设置名字了。

    如果您想直接设置名称,则可以先创建一个命名列表:

    named_cols = setattr(as.list(cols), 'names', cols) 
    DT[, lapply(named_cols, function(x) sum(value<=x)), by=.(ID, year)]
    #    ID year 100 102 105 108 112
    # 1:  1 2003   0   2   3   3   3
    # 2:  1 2004   0   0   2   3   3
    # 3:  2 2005   0   0   0   2   3
    # 4:  2 2006   0   0   0   0   3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-12
      • 2021-10-11
      • 1970-01-01
      • 2019-08-22
      • 2019-04-08
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多