[英]Filling in the missing field for column in data frame in R
I have the following columns: 我有以下专栏:
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
. . .
. . .
. . .
Basically there are 4 box types (A, B, C, D) and for each casenum, if there's no balls in a box, it doesn't appear. 基本上有4种盒子类型(A,B,C,D),对于每个盒子,如果盒子里没有球,它就不会出现。 However, I want each box type to appear like this.
但是,我希望每个盒子类型都像这样。
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
. . .
. . .
. . .
is there an easy way to do that? 有一个简单的方法吗?
Or I can have in in a format 或者我可以使用某种格式
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
. . . . .
. . . . .
I used while loop to achieve this, but I was wondering if there's a way of doing it (using some libraries that I'm not aware of) without using loops. 我使用while循环来实现这一点,但我想知道是否有一种方法(使用一些我不知道的库)而不使用循环。
I would create a new data.frame with all the possible combinations of box and casenum and then add the number of balls: 我会创建一个新的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
Its the job for xtabs
in base R where df
is your data frame: 它是基础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
We can use acast
from reshape2
我们可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.