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

Create formula inside loop over column names

$
0
0

I would like to loop through columns in a data set and use the name of the column to aggregate the data set. However, I am getting an error when I try to feed through the column name into the aggregate function:

"Error in model.frame.default(formula = cbind(SurveyID) ~ Panel + Category + : variable lengths differ (found for 'i')"

Once I can store this is a temp file, I will add the temp file to a permanent dataset; however, I can't get past this part. Any help would be so much appreciated!

#example of my data:
    df <- data.frame("SurveyID" = c('A','B','C','D'), "Panel" = c('E','E','S','S'), "Category" = c(1,1,2,3), "ENG" = c(3,3,1,2), "PAR"
    = c(3,1,1,2), "REL" = c(3,1,1,2), "CLC"= c(3,1,1,2))

#for loop to get column name to include as part of the aggregate function
    for (i in colnames(df[4:7])) {
      print (i)
     temp <-  data.frame(setNames(aggregate(cbind(SurveyID) ~ Panel + Category + i, data = df, FUN = length), c("Panel","GENDER", "Favlev", "Cnt")))       
}

Viewing all articles
Browse latest Browse all 201919

Trending Articles



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