Fill missing combinations in a dataframe

前端 未结 1 1000
死守一世寂寞
死守一世寂寞 2020-12-02 02:14

My example dataset:

df <- data.frame(
 REGION = c(\"REGION A\", \"REGION A\", \"REGION B\"), 
 CATEGORY = c(\"A\", \"B\", \"B\"), 
 VALUE1 = c(2,3,4),
 VA         


        
相关标签:
1条回答
  • 2020-12-02 03:04

    Using complete from tidyr:

    library(tidyr)
    as.data.frame(complete(df,REGION,CATEGORY,fill=list(VALUE1=0,VALUE2=0)))
    

    Output:

        REGION CATEGORY VALUE1 VALUE2
    1 REGION A        A      2      1
    2 REGION A        B      3      2
    3 REGION B        A      0      0
    4 REGION B        B      4      3
    

    If there are many variables, you could also just do as.data.frame(complete(df,REGION,CATEGORY)) and replace the NA's afterwards.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题