Inserting a new row to data frame for each group id

后端 未结 3 1200
萌比男神i
萌比男神i 2021-01-02 05:47

I\'ve looked extensively on stack overflow for a solution, but have yet to find one that works for me. I have a data frame that looks something like this:

id         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 06:29

    We can do this with data.table. Convert the 'data.frame' to 'data.table' (setDT(df1)), grouped by 'id', get the last row with tail, assign the 'latitude' and 'longitude' with the new values, rbind with the original dataset and order by 'id'.

    library(data.table)
    rbind(setDT(df1), df1[, tail(.SD, 1) , by = id
            ][, c("latitude", "longitude") := .(394681.4,  6017550)
             ])[order(id)]
    #    id  time latitude longitude
    #1:  A 11:10 381746.0   6008345
    #2:  A 11:11 381726.2   6008294
    #3:  A 11:11 394681.4   6017550
    #4:  B 10:56 381703.0   6008214
    #5:  B 10:57 381679.7   6008134
    #6:  B 10:57 394681.4   6017550
    #7:  C  4:30 381654.4   6008083
    #8:  C  4:31 381629.2   6008033
    #9:  C  4:31 394681.4   6017550
    

    Or using dplyr, with similar methodology

    library(dplyr)
    df1 %>%
       group_by(id) %>%
       summarise(time = last(time)) %>%
       mutate(latitude = 394681.4, longitude = 6017550) %>% 
       bind_rows(df1, .) %>% 
       arrange(id)
    

提交回复
热议问题