Your call to mapply(...)
is more complex than it needs to be:
counts <- mapply(FUN= function(z,y) aggregate(d[ , y], by=d[z], FUN=length),
c1, "user_id")
If all you want to do is automate renaming the column x
in each dataframe to something else, this will work:
# rename all "x" columns
for (i in 1:length(counts))
colnames(counts[[i]])[ncol(counts[[i]])]<- varNames[i]
To address your core issue, I'd need to see an example of what you mean by "graph the frequency of the top choices for each grouping combination."
EDIT (Response to OP's comment)
If your intermediate goal is to combine everything into a singe data frame, then there is an easier way. Note that this leaves the aggregated columns named as x
until the end.
counts <- mapply(FUN= function(z,y) aggregate(d[ , y], by=d[z], FUN=length),
c1, "user_id")
mrg <- lapply(counts,function(df)merge(d,df)[,c("user_id","x")])
mrg <- do.call(cbind,lapply(mrg,function(df)merge(d,df,by="user_id")$x))
colnames(mrg) <- varNames
result <- cbind(d,mrg)
result
# user_id choice cond1 gender cond1Ct cond1_GenderCt
# 1 1 apple a1 F 2 1
# 2 2 banana a1 M 2 2
# 3 3 banana a2 F 3 2
# 4 4 apple a1 M 2 1
# 5 5 banana a2 F 3 2
# 6 6 banana a1 M 2 2
# 7 7 apple a2 F 1 1
# 8 8 banana a2 M 3 1
# 9 9 banana a3 F 3 2
# 10 10 apple a3 M 1 1
# 11 11 banana a3 F 3 2
# 12 12 banana a3 M 3 1
The first use of lapply(...)
mrg <- lapply(counts,function(df)merge(d,df)[,c("user_id","x")])
creates a list of data frames wherein each associates user_id
with the count for the appropriate combination. Then,
mrg <- do.call(cbind,lapply(mrg,function(df)merge(d,df,by="user_id")$x))
combines the x
column from each into a single data frame ordered properly by user_id
. Finally,
result <- cbind(d,mrg)
combines the columns with the original data frame d
, which is already in user_id
order.
Again, it would be much better to understand your ultimate goal, as there is almost certainly a way to achieve it without going through all this.