Skip to content

Instantly share code, notes, and snippets.

@Awuor87
Created April 4, 2017 15:13
Show Gist options
  • Save Awuor87/46d05cdb893d3e84f169e38901053a44 to your computer and use it in GitHub Desktop.
Save Awuor87/46d05cdb893d3e84f169e38901053a44 to your computer and use it in GitHub Desktop.
Sample Loop Code in R
# Define 2^2 test matrix
FullFact.2.2 <- function() {
a <- c(-1,1,-1,1)
b <- c(-1,-1,1,1)
ab <- a *b
df <- data.frame(a,b, ab)
rownames(df)<- c("(1)", "a", "b", "ab")
return(df)
}
(ff22<- FullFact.2.2())
#select number of rows
rowct<- nrow(ff22)
#select number of cloumns
colct <- ncol(ff22)
# copy that row to the end of ff22(loops), you can use rowbind as well
for (xrow in 1:rowct) {
ff22[xrow+rowct,]<- ff22[xrow,]
}
#set vector C to four 1s followed by four -1s
c<- c(rep(-1,rowct), rep(1,rowct))
#Add that vector to the last column to ff22
ff22<- cbind(ff22, c)
ff22
#Multiply the new factor by all preceeding columns
#for each column "xcol" of the original "colct" columns
for (xcol in 1:colct){
ff22[, colct+1+xcol] <- ff22[, colct+1]* ff22[, xcol]
newname<-paste(colnames(ff22)[xcol], colnames(ff22)[colct+1], sep="")
colnames(ff22)[colct+1+xcol]<- newname
}
#set the name of the newest row to "c"
#concatenation of the early row name and "c"
rownames(ff22)[rowct+1]<-"c"
for (xrow in 2:rowct) {
rownames(ff22)[rowct+xrow]<- paste(rownames(ff22)[xrow], "c", sep="")
}
ff22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment