Handling missing combinations of factors in R

后端 未结 3 1437
离开以前
离开以前 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:33

    Two years late, but I had the same problem and came up with this plyr solution:

    dat <- data.frame(f1 = factor(c(1,2,2)), f2 = factor(c("A","A","B")), v1 = c(23,45,27))
    
    newdat <- ddply(dat, .(f1,f2), numcolwise(function(x) {if(length(x)>0) x else 0.0}), .drop=F)
    
    > newdat
      f1 f2 v1
    1  1  A 23
    2  1  B  0
    3  2  A 45
    4  2  B 27
    

提交回复
热议问题