I have a dataframe (DF_melted) which I obtained by melting some other dataset. The DF_melted dataframe has columns "month","A","B","C","D","E","F". From the following code using dcast, I am able to get a dataframe which contains value of mean of the variable for each combination of "A" and "month". This all works fine and as expected.
dcast_data<-dcast(DF_Melted,
month+A~variable,
fun.aggregate = mean)
Question- On lines of the above code, I want to run a for loop to automatically obtain the dataset (using dcast) for relationship of month+A, month+B, month+C, month+D . I am unable to figure out about how to substitute 'A' (or B, C, D) in a paremetric manner.
I tried the following code where I reference to A,B,C,D as per their column number in DF_melted and it works:
for(j in seq(2,5, by=1)) #'A' is 2nd column, 'D' is 5th column
{
dcast_data<-dcast(DF_Melted,
month+DF_Melted[,j]~variable,
fun.aggregate = mean)
FinalDF<-cbind(FinalDF,dcast_data)
}
Although the above works, I am wondering if there is a smarter way to do the above without referencing the column number of the data frame?
Eventually my intention is to get a dataframe 'FinalDF' so that I could use it to plot the month v/s variable graph for each category of A, B, C, D. So doing this data reshaping automatically would be an immense help.