2017-05-13 44 views
1

在數據幀列我有以下的列:灌裝在缺少字段中的R

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,如果有沒有球在一個盒子裏,它不會出現。不過,我希望每個盒子類型都像這樣出現。

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循環來實現這一目標有,但我不知道是否有(使用一些庫,我不知道的)做這件事的方式不使用循環。

回答

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 
1

我會創建一個盒子和casenum的所有可能的組合新data.frame,然後添加球的數量:

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

我們可以使用acastreshape2

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 
+1

感謝您的替代答案。 – user98235