Assignment of values ​​in the first rows of groups in the data table.

I would like to assign only those values ​​in the first line of the group to data.table.

For example (simplified): my data.table- DTwith the following contents

x v  
1 1  
2 2  
2 3  
3 4  
3 5  
3 6 

keyof DT- x.
I want to refer to every first line of the group.

This works fine: DT[, .SD[1], by=x]

x v  
1 1  
2 2  
3 4 

Now I want to assign only those values ​​from vto 0.

But none of this works:

DT[, .SD[1], by=x]$v <- 0  
DT[, .SD[1], by=x]$v := 0  
DT[, .SD[1], by=x, v:=0]

I searched for R-help from the package and any links, but I just can't get it to work.
I found there entries that said this would not work, but there are no examples / solutions that would help me.

I would be very happy for any suggestions.

( , data.frame... )

:

:

x v  
1 0  
2 0  
2 3  
3 0  
3 5  
3 6  

:

DT[, .SD[1], by=x] <- DT[, .SD[1], by=x][, v:=0]
+4
2

Roland, , . v, .

DT[, v := c(0L, v[-1]), by = x]   ## must have the "L" after 0, as 0L

DT
#    x v
# 1: 1 0
# 2: 2 0
# 3: 2 3
# 4: 3 0
# 5: 3 5
# 6: 3 6

: j v := c(integer(1), v[-1])

+3

:

 DT[,v:={v[1]<-0L;v}, by=x]
 DT
 #  x v
 #1: 1 0
 #2: 2 0
 #3: 2 3
 #4: 3 0
 #5: 3 5
 #6: 3 6

 DT[DT[, .I[1], by=x]$V1, v:=0]
 DT
 #   x v
 #1: 1 0
 #2: 2 0
 #3: 2 3
 #4: 3 0
 #5: 3 5
 #6: 3 6
+1

All Articles