如何在数据框中完成缺失因子水平?

时间:2016-10-10 15:34:19

标签: r dataframe

让我假装我有这样的事情:

df <- data.frame(
      PERSON = c("Peter", "Peter", "Marcel" , "Lisa", "Lisa"),        
      FRUIT = c("Apple", "Peach","Apple", "Apple", "Peach" ), 
      A = c(100, 200, 100, 200, 300), 
      B=c(1,2,3,4,5) )
df$PERSON <- as.factor(df$Person)
df$FRUIT <- factor(df$FRUIT, levels = c("Apple", "Peach", "Coconut"))

结果

str(df): 'data.frame':  5 obs. of  4 variables:
$ PERSON: Factor w/ 3 levels "Lisa","Marcel",..: 3 3 2 1 1
$ FRUIT : Factor w/ 3 levels "Apple","Peach",..: 1 2 1 1 2
$ A     : num  100 200 100 200 300
$ B     : num  1 2 3 4 5

我想扩展这些数据框架,以便每个PERSON都有所有级别的FRUIT,如下所示:

 Person FRUIT   A B
1  Peter Apple 100 1
2  Peter Peach 200 2
3  Peter Coconut 0 0
4 Marcel Apple 100 3
5 Marcel Peach 0 0
6 Marcel Coconut 0 0
7   Lisa Apple 200 4
8   Lisa Peach 300 5
9   Lisa Coconut 0 0

AB的缺失值应填入0。

我试过了tidyr::complete(df$FRUIT, 0),但似乎我错误地使用了这个函数。

提前致谢

1 个答案:

答案 0 :(得分:12)

complete将第一个参数作为&#39;数据&#39;,然后是要展开的列。默认情况下,fill为NA,但我们可以通过在list中指定它来将其更改为0.

complete(df, PERSON, FRUIT, fill = list(A=0, B = 0))