Search code examples
rdata.tablespread

Spreading values on data.tables


I'm new to R and I would like to know if there is a library for spreading and by spreading I mean that for example if I have this data.table:

DT <- data.table(V1 = c(1L,2L), V2 = LETTERS[1:4], V4 = 1:4)

and I assing 15 to the V4 column:

DT$V4 = 15

the values will be adjusted so that the sum is now 15:

DT <- data.table(V1 = c(1L,2L), V2 = LETTERS[1:4], V4 = c(1.5,3,4.5,6)).

(The new values result from being multiplied by 15/sum(column) --> 15 / 10)

This is the easiest example of what I have to do, that's why I ask if there is a library.


Solution

  • You can use below to calculate the number to be multiplied 15/10=1.5 and then multiply it by .I

    DT <- data.table(V1 = c(1L,2L), V2 = LETTERS[1:4], V4 = 1:4)
    DT$V4 = 15
    DT[,V4:=.I*V4/sum(seq(.N))]
    
    DT
    # V1 V2  V4
    # 1:  1  A 1.5
    # 2:  2  B 3.0
    # 3:  1  C 4.5
    # 4:  2  D 6.0