Handling missing combinations of factors in R

后端 未结 3 1435
离开以前
离开以前 2020-12-11 02:54

So, I have a data frame with two factors and one numeric variable like so:

>D
f1 f2 v1 
1   A  23
2   A  45
2   B  27
     .
     .
     .
3条回答
  •  感情败类
    2020-12-11 03:23

    I add the tidyr solution, spreading with fill=0 and gathering.

    library(tidyr)
    df %>% spread(f2, v1, fill=0) %>% gather(f2, v1, -f1)
    
    #  f1 f2 v1
    #1  1  A 23
    #2  2  A 45
    #3  1  B  0
    #4  2  B 27
    

    You could equally do df %>% spread(f1, v1, fill=0) %>% gather(f1, v1, -f2).

提交回复
热议问题