I would like to copy the text of a data frame's column names one-by-one in a for loop. My code seems to return NULL values from the column name argument.
More broadly, I want to create a summary by factor of each of several columns.
# Create an example data frame
df <- data.frame( c( "a", "b", "c", "b", "c"), c( 6, 4, 10, 9, 11), c( 1, 3, 5, 3, 6))
colnames(df) <- c( "Group", "Num.Hats", "Num.Balls")
Now I want to loop over columns two and three, creating a data object storing the summary statistics by Group. The point is to get a look at how groups A, B, and C differ from one another with respect to balls and with respect to hats.
My code looks like this:
# Evaluate stats of each group
for (i in 2:3){
assign(paste0("Eval.", colnames(df[[i]])), tapply(df[,i], df$Group, summary))
}
I am getting a single object called "Eval." with the summary statistics for Num.Balls. To be clear, I would like two objects, one called "Eval.Num.Hats" and one called "Eval.Num.Balls".
If colnames() cannot be used in this way, is there another function to achieve my desired result? Alternatively, I'd be open to another solution if the loop is not required. I'd love to learn something new, but please explain thoroughly as I'm still a beginner (which is probably clear :P).