user13203033
user13203033

Reputation: 133

How to retain original variable names in R when using Aggregate?

I am running the following aggregate function - but all the resulting variables are named V1, V2, etc.

cadincmerge_ag0 <- aggregate(cbind(cadincmerge$violentIncidents, cadincmerge$nonviolentIncidents, cadincmerge$allPart1s, cadincmerge$robberies, cadincmerge$assaults, cadincmerge$homs_shootings, cadincmerge$propcrime, cadincmerge$weapinv, cadincmerge$proactivity , cadincmerge$proactivity_no_ce, cadincmerge$ce, cadincmerge$footpatrol , cadincmerge$bizcheck, cadincmerge$trafstop, cadincmerge$invstop , cadincmerge$warsvc, cadincmerge$fi) ~ District + pnum_4wk, data = cadincmerge, FUN = sum, na.rm=TRUE)

Is there an easier way to retain the original variable names without having to do rename(name = V1, etc.) it is very tedious to do that way.

Upvotes: 0

Views: 387

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

Don't use $ to access column values when using formula syntax. You can mention the names directly.

aggregate(cbind(violentIncidents, nonviolentIncidents, allPart1s, robberies, 
         assaults, homs_shootings, propcrime, weapinv, proactivity, 
         proactivity_no_ce, ce, footpatrol , bizcheck, trafstop, invstop , warsvc,
        fi) ~ District + pnum_4wk, data = cadincmerge, FUN = sum, na.rm=TRUE)

Moreover, you can look into dplyr when you want to aggregate multiple variables where you can specify columns to aggregate by position or pattern in names, or a range of columns etc instead of writing all variables by hand.

Upvotes: 2

Related Questions