Fill in missing rows in R

后端 未结 2 500
耶瑟儿~
耶瑟儿~ 2021-01-17 02:29

Suppose I have a data frame which looks like this

ID  A   B   C   D   Month
1   X   M   5   1   3
1   X   K   4   2   4
1   X   K   3   7   5
1   X   K   2           


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-17 02:48

    Maybe something like this would work for your needs:

    library(dplyr)
    
    mydf %>%
      full_join(expand.grid(ID = unique(mydf$ID), Month = 1:6)) %>%
      group_by(ID) %>%
      mutate(A = replace(A, is.na(A), unique(na.omit(A)))) %>%
      arrange(ID, A, Month) %>%
      replace(., is.na(.), 0)
    # Joining by: c("ID", "Month")
    # Source: local data frame [18 x 6]
    # Groups: ID
    # 
    #    ID A B C D Month
    # 1   1 X 0 0 0     1
    # 2   1 X 0 0 0     2
    # 3   1 X M 5 1     3
    # 4   1 X K 4 2     4
    # 5   1 X K 3 7     5
    # 6   1 X K 2 6     6
    # 7   2 Y L 5 8     1
    # 8   2 Y L 2 3     2
    # 9   2 Y M 5 1     3
    # 10  2 Y 0 0 0     4
    # 11  2 Y K 2 7     5
    # 12  2 Y M 2 8     6
    # 13  3 Z K 5 3     1
    # 14  3 Z M 6 3     2
    # 15  3 Z M 5 8     3
    # 16  3 Z K 4 2     4
    # 17  3 Z 0 0 0     5
    # 18  3 Z 0 0 0     6
    

提交回复
热议问题