R累积总和基于其他列

时间:2015-06-02 23:23:02

标签: r cumulative-sum

我有一个data.frame如下。数据按列txt排序,然后按列val排序。 summ列是val colummn中的值和来自前一行的summ列值的总和,条件是当前行和前一行在txt列中具有相同的值...我怎么能在R中执行此操作?

txt=c(rep("a",4),rep("b",5),rep("c",3))
val=c(1,2,3,4,1,2,3,4,5,1,2,3)
summ=c(1,3,6,10,1,3,6,10,15,1,3,6)
dd=data.frame(txt,val,summ)
> dd
   txt val summ
1    a   1    1
2    a   2    3
3    a   3    6
4    a   4   10
5    b   1    1
6    b   2    3
7    b   3    6
8    b   4   10
9    b   5   15
10   c   1    1
11   c   2    3
12   c   3    6

1 个答案:

答案 0 :(得分:2)

如果“最早”(英文写得更恰当“最早”)是指最近,这是你预期输出所隐含的,那么你所说的是什么是累积金额。您可以cumsum()分别对txt dd <- data.frame(txt=c(rep("a",4),rep("b",5),rep("c",3)), val=c(1,2,3,4,1,2,3,4,5,1,2,3) ); dd$summ <- ave(dd$val,dd$txt,FUN=cumsum); dd; ## txt val summ ## 1 a 1 1 ## 2 a 2 3 ## 3 a 3 6 ## 4 a 4 10 ## 5 b 1 1 ## 6 b 2 3 ## 7 b 3 6 ## 8 b 4 10 ## 9 b 5 15 ## 10 c 1 1 ## 11 c 2 3 ## 12 c 3 6 的每个function love.load() ball = love.graphics.newImage('ball.png') speed = 300 x, y = 0,0 soccer = love.graphics.newImage('soccer.png') speed2 = 300 x1, y1 = 20,20 end function love.update(dt) if love.keyboard.isDown("right") then x = x + (speed*dt) end if love.keyboard.isDown("left") then x = x - (speed*dt) end if love.keyboard.isDown("up") then y = y - (speed*dt) end if love.keyboard.isDown("down") then y = y + (speed*dt) end if love.keyboard.isDown("d") then x1 = x1 + (speed2*dt) end if love.keyboard.isDown("a") then x1 = x1 - (speed2*dt) end if love.keyboard.isDown("w") then y1 = y1 - (speed2*dt) end if love.keyboard.isDown("s") then y1 = y1 + (speed2*dt) end end function love.draw() love.graphics.draw(ball, x,y,0,0.5,0.5) love.graphics.draw(soccer, x1,y1,0,0.25,0.25) love.graphics.setBackgroundColor(0,255,0) end 组进行申请:

<anon>:5:9: 5:14 error: mismatched types:
 expected `&core::result::Result<&str, ()>`,
    found `core::result::Result<_, _>`
(expected &-ptr,
    found enum `core::result::Result`) [E0308]
<anon>:5         Ok(s) => match s.parse() {
                 ^~~~~
相关问题