rdplyrtidyrdata-manipulationtidy

Increment the vector value as long as the row number


I have 2 datasets that I would like to merge. But before that, I would like to increment ID as tail(df1$ID, n=1) + 1 as long as the last row of the df2

 df1 <- data_frame(ID = c(1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples" )
df2 <- data_frame(ID = "I NEED TO DEFINE", valueA = seq(0.1,0.4,0.1),  Category= "Apples2")


tail(df1$ID, n=1)

Expected Answer

 ID ValueA Category
     1    0.1 Apples  
     2    0.2 Apples  
     3    0.3 Apples  
     4    0.4 Apples  
     5    0.1 Apples2 
     6    0.2 Apples2 
     7    0.3 Apples2 
     8    0.4 Apples2 

How to get around this? Many thanks in advance.


Solution

  • You're 90% of the way there! Define end as the ID value for the last row of df1, and increment that with ::

    end <- tail(df1$ID, n=1)
    df2$ID <- (end+1):(end+nrow(df2))
    bind_rows(df1, df2)
    

    Which gave me exactly your expected output.