I have a for loop that doesn't seem to update the dataframe (all_perms). Hard-coding two loops works just fine. I can't understand the mistake.
Here is my example code:
#preparation
data <- c("MARRIED", "DIVORCED", "MARRIED", "SEPARATED", "DIVORCED", "NEVER MARRIED", "DIVORCED", "DIVORCED", "NEVER MARRIED", "MARRIED", "MARRIED", "MARRIED", "SEPARATED", "DIVORCED", "NEVER MARRIED", "NEVER MARRIED", "DIVORCED", "DIVORCED", "MARRIED")
observed <- c(table(data))
n <- sum(observed)
k <- length(observed)
expProb =rep(1/k, k)
pObs = dmultinom(sort(observed, decreasing=TRUE), size=n, expProb)
counts <- seq(0, n, by = 1)
kCounts <- matrix(,nrow=n+1, ncol=k)
for (i in 1:k){
kCounts[,i] <- counts
}
all_perm <- merge(kCounts[,1], as.data.frame(kCounts[,2]),all=TRUE)
all_perm <- all_perm[rowSums(all_perm) <= n,]
#WITHOUT FOR LOOP
#column three and four
all_perm <- merge(all_perm, as.data.frame(kCounts[,3]),all=TRUE)
all_perm <- all_perm[rowSums(all_perm) <= n,]
dim(all_perm)
#shows correct 3 columns
all_perm <- merge(all_perm, as.data.frame(kCounts[,4]),all=TRUE)
all_perm <- all_perm[rowSums(all_perm) <= n,]
dim(all_perm)
#shows correct 4 columns
#THE FOR LOOP THAT DOESN'T WORK
#reset first two columns
all_perm <- merge(kCounts[,1], as.data.frame(kCounts[,2]),all=TRUE)
all_perm <- all_perm[rowSums(all_perm) <= n,]
#the for loop
for (i in 3:k){
all_perm <- merge(all_perm, as.data.frame(kCounts[,i]),all=TRUE)
all_perm <- all_perm[rowSums(all_perm) <= n,]
print(dim(all_perm))
}
#first iteration good (column 3), fourth not being added.
I tried using a while loop instead, but also that didn't work. I really don't get why the for loop is not working any help would be appreciated.