Inserting a new row to data frame for each group id

后端 未结 3 1204
萌比男神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:20

    Using dplyr

       library(dplyr)
    
     # data:   
        df <- structure(list(id = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("A", 
        "B", "C"), class = "factor"), time = structure(c(3L, 4L, 1L, 
        2L, 5L, 6L), .Label = c("10:56", "10:57", "11:10", "11:11", "4:30", 
        "4:31"), class = "factor"), latitude = c(381746, 381726.2, 381703, 
        381679.7, 381654.4, 381629.2), longitude = c(6008345L, 6008294L, 
        6008214L, 6008134L, 6008083L, 6008033L)), .Names = c("id", "time", 
        "latitude", "longitude"), row.names = c(NA, -6L), class = c("tbl_df", 
        "tbl", "data.frame"))
    
     # code: 
    
        df %>% group_by(id) %>% 
            do({ df <- . 
                 last_row           <- df %>% slice(n())
                 last_row$latitude  <- 394681.4
                 last_row$longitude <- 6017550
                 df                 <- bind_rows(df, last_row)
            })
    

提交回复
热议问题