【问题标题】:Refer to column numbers by using a number in another column when using data.table使用 data.table 时,通过在另一列中使用数字来引用列号
【发布时间】:2023-03-15 19:16:02
【问题描述】:

我有如下数据表:

library(data.table)

dt <- data.table("one" =c(100,200,300,400,500,600))
dt <- dt[,two:=round(one*1.05,0)][,three:=round(two*1.03,0)][,four:=round(three*1.07,0)][,five:=round(four*1.05,0)][,six:=round(five*1.1,0)][,curr:=c(3,4,5,6)]

> dt
   one two three four five six curr
1:  100 105   108  116  122 134    3
2:  200 210   216  231  243 267    4
3:  300 315   324  347  364 400    5
4:  400 420   433  463  486 535    6
5:  500 525   541  579  608 669    3
6:  600 630   649  694  729 802    4

我想使用 data.table 逐行抓取“curr”列中的数字,并计算表中该列号及其前一列的平均值。例如,对于第一行,它将在“第三”列中获取 108 的值,在“第二”列中获取 105 的值并给出 106.5。对于第二行,它将取 231 和 216 等的平均值。

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    这将完成工作:

    # create a column with row positions
    dt[, rowpos := .I]
    
    # create a function that will be applied to every pair of column and row position
    myfunc <- function(colpos,rowpos) { mean(c(as.matrix(dt)[rowpos,colpos], 
                                               as.matrix(dt)[rowpos,(colpos-1)])) }
    
    # apply function
    dt[ , var := myfunc(curr, rowpos) , by = rowpos]
    
    #>    one two three four five six curr rowpos   var
    #> 1: 100 105   108  116  122 134    3      1 106.5
    #> 2: 200 210   216  231  243 267    4      2 223.5
    #> 3: 300 315   324  347  364 400    5      3 355.5
    #> 4: 400 420   433  463  486 535    6      4 510.5
    #> 5: 500 525   541  579  608 669    3      5 533.0
    #> 6: 600 630   649  694  729 802    4      6 671.5
    

    【讨论】:

    • 谢谢。不幸的是,我还没有声望你的答案。
    【解决方案2】:

    这是另一个解决方案(回答我自己的问题):

    dt[, rowpos := .I]  #Using Rafa's idea above
    dt[, c("new","new_prev") := .SD[, c(curr,curr-1), with=FALSE], by = rowpos]
    dt$mean <- rowMeans(subset(dt, select = c(new, new_prev)),na.rm=TRUE)
    
    > dt 
      one two three four five six curr rowpos new new_prev  mean
    1: 100 105   108  116  122 134    3      1 108      105 106.5
    2: 200 210   216  231  243 267    4      2 231      216 223.5
    3: 300 315   324  347  364 400    5      3 364      347 355.5
    4: 400 420   433  463  486 535    6      4 535      486 510.5
    5: 500 525   541  579  608 669    3      5 541      525 533.0
    6: 600 630   649  694  729 802    4      6 694      649 671.5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多