Extend an irregular sequence and add zeros to missing values

前端 未结 9 2280
深忆病人
深忆病人 2020-12-19 08:36

I have a data frame with a sequence in \'col1\' and values in \'col2\':

col1 col2
2     0.02
5     0.12
9     0.91
13    1.13

I want to exp

9条回答
  •  無奈伤痛
    2020-12-19 09:10

    Just to add a different point of view, consider that what you have can be seen as a sparse vector, i.e. a vector whose only the non-zero values are defined. Sparse vectors are implemented by the Matrix package in R. If df is your initial data.frame, try:

    require(Matrix)
    data.frame(col1=seq_len(max(df$col1)),
          col2=as.vector(sparseVector(df$col2,df$col1,max(df$col1))))
    #   col1 col2
    #1     1 0.00
    #2     2 0.02
    #3     3 0.00
    #4     4 0.00
    #5     5 0.12
    #6     6 0.00
    #7     7 0.00
    #8     8 0.00
    #9     9 0.91
    #10   10 0.00
    #11   11 0.00
    #12   12 0.00
    #13   13 1.13
    

    The same result in a one-liner base R:

    data.frame(col1=seq_len(max(df$col1)),
       col2=`[<-`(numeric(max(df$col1)),df$col1,df$col2))
    

提交回复
热议问题