Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

How to extract the name of a column from a data frame? Name to be used as text in a for loop

$
0
0

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")

example data frame with each group member's number of hats and number of 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).


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>