Filling data frame with previous row value

前端 未结 7 598
孤街浪徒
孤街浪徒 2020-12-29 13:02

I have a data frame that has 2 columns.

column1 has random numbers in column2 is a place holding column for what i want column3 to look like

  random         


        
7条回答
  •  离开以前
    2020-12-29 14:05

    A loop along the following lines should do the trick for you -

    for(i in seq(nrow(df)))
    {
      if (df[i,"v1"] == 0) df[i,"v1"] <- df[i-1,"v1"]
    }
    

    Output -

    > df
       v1 somedata
    1   1       33
    2   2       24
    3   1       36
    4   0       49
    5   2       89
    6   2       48
    7   0        4
    8   1       98
    9   1       60
    10  2       76
    > 
    > for(i in seq(nrow(df)))
    + {
    +   if (df[i,"v1"] == 0) df[i,"v1"] <- df[i-1,"v1"]
    + }
    > df
       v1 somedata
    1   1       33
    2   2       24
    3   1       36
    4   1       49
    5   2       89
    6   2       48
    7   2        4
    8   1       98
    9   1       60
    10  2       76
    

提交回复
热议问题