我想使用以下代码创建数据集,目的是在每个组之间添加一个空行,并在每个处理之间添加三个空行。我希望它看起来像以下数据集。
value group treatment
39.7 A 1
53.5 A 1
51.1 A 1
67.8 A 1
84.8 B 1
80.3 B 1
79.6 B 1
84.3 B 1
31.0 C 2
32.0 C 2
33.0 C 2
34.0 C 2
1.0 D 2
2.0 D 2
3.0 D 2
4.0 D 2
我写了一个双for
循环,但它不能正常工作。我无法弄清楚。谁能告诉我它有什么问题?
mydata <- data.frame(value=c(39.7,53.5,51.1,67.8,84.8,80.3,79.6,84.3,31,32,33,34,1,2,3,4),group=c("A","A","A","A","B","B","B","B","C","C","C","C","D","D","D","D"),treatment=c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2))
blank <- data.frame(value=NA,group="NA",treatment=NA)
blank1 <- data.frame(value=c(NA,NA,NA),group=c("NA","NA","NA"),treatment=c(NA,NA,NA))
uni<-unique(mydata$treatment)
b<-length(uni)
out <- c()
out1<-c()
for (i in 1:b) {
emp<-subset(mydata,treatment==uni[i])
uni1<-unique(emp$group)
c<-length(uni1)
for (j in 1:c){
emp1<-subset(subset(mydata,treatment==uni[i]),group==uni1[j])
stack<-rbind(emp1,blank)
out<-rbind(stack,out)
}
stack1<-rbind(out,blank1)
out1<-rbind(stack1,out1)
}
答案 0 :(得分:1)
我无法想象在这种模式下使用空白行的数据的实际原因,所以我假设它只是用于打印:
printables <- lapply(
split(mydata,mydata$treatment),
function(t)
split(t,as.character(t$group)))
for (t in seq_along(printables)){
for(g in seq_along(printables[[t]])){
print(printables[[t]][[g]],row.names=FALSE)
cat('\n')
}
cat('\n\n')
}