填写R中数据框中列的缺失字段

时间:2017-05-13 17:02:17

标签: r dataframe

我有以下专栏:

casenum  box type  number of balls in the box
  1         A               10
  1         B               20
  2         B               1
  2         C               2
  2         D               12
  3         A               10
  3         B               20
  3         C               1
  3         D               2
  .         .               .
  .         .               .
  .         .               .

基本上有4种盒子类型(A,B,C,D),对于每个盒子,如果盒子里没有球,它就不会出现。但是,我希望每个盒子类型都像这样。

casenum  box type  number of balls in the box
  1         A               10
  1         B               20
  1         C               0
  1         D               0
  1         A               0
  2         B               1
  2         C               2
  2         D               12
  3         A               10
  3         B               20
  3         C               1
  3         D               2
  .         .               .
  .         .               .
  .         .               .

有一种简单的方法吗?

或者我可以使用格式

casenum    ballnum in A     ballnum in B     ballnum in C     ballnum in D 
  1            10                20              0                  0
  2            0                  1              2                 12
  3            10                20              1                  2
  .            .                  .              .                  .
  .            .                  .              .                  .

我使用while循环来实现这一点,但我想知道是否有办法(不使用循环使用一些我不知道的库)。

3 个答案:

答案 0 :(得分:1)

我会创建一个新的data.frame,其中包含box和casenum的所有可能组合,然后添加球的数量:

df<-read.table(text="casenum  box  number
1         A               10
1         B               20
2         B               1
2         C               2
2         D               12
3         A               10
3         B               20
3         C               1
3         D               2", header=T)

dftot <- data.frame(casenum=rep(1:3, each=4), box=c("A","B","C","D"), stringsAsFactors = F) #create new df with all combinations of casenum and box
dftot$number <- df$number[match(paste(dftot$casenum,dftot$box),paste(df$casenum, df$box))] #add numbers from your original data.frame
dftot$number[is.na(dftot$number)] <- 0 #change all NA values to 0

答案 1 :(得分:1)

基础R中xtabs的工作,其中df是您的数据框:

xtabs(number~., df)

#       box
#casenum  A  B  C  D
#      1 10 20  0  0
#      2  0  1  2 12
#      3 10 20  1  2

答案 2 :(得分:1)

我们可以使用acast

中的reshape2
library(reshape2)
acast(df, casenum~box, fill=0)
#   A  B C  D
#1 10 20 0  0
#2  0  1 2 12
#3 10 20 1  2