I would suggest using the function expand.grid
which will automatically generate all the combinations.
Also in your code unique(planningItems["Subject"])
, it will return a data frame which is actually not a good idea for this case. A vector would be better.
Here is my code:
uniquesubject = unique(dfSubClass$Subject)
uniqueclass = unique(dfSubClass$Class)
newDF=expand.grid(uniquesubject,uniqueclass)
If using for
loops, the main issue in your code is about the rbind
function. Here is my code:
uniquesubject = unique(dfSubClass$Subject)
uniqueclass = unique(dfSubClass$Class)
newDF = data.frame()
for (Subject in 1:length(uniquesubject)){
for (Class in 1:length(uniqueclass)){
newDF=rbind(newDF,data.frame("Subject"=uniquesubject[Subject],"Class"=uniqueclass[Class]))
}
}
I think the main different to your code is that I created a dataframe inside the rbind()
instead of creating a vector using c()
. This is to make sure the result is in dataframe structure instead of a matrix.
5
solved creating data frame using for loop for string data in R