Another beginner question for dataframe aggregation.
I want to aggregate multiple columns in a dataframe using values multiple columns. Yes I have seen some previous similar post. However I think the difference here is I'm trying to aggregate based on multiple columns.
For example my data frame:
column1 column2 column3 V1 V2
A a 7 90 600
A a 7 90 600
A b 7 80 600
A b 6 70 5000
A b 6 70 5000
....
Aggregate and sum the numbers in V1 and V2:
column1 column2 column3 V1 V2
A a 7 180 1200
A b 7 80 600
A b 6 140 10000
....
Here's my minimized data and code:
#generate minimal sample data
column1 <- c("S104259","S2914138" ,"S999706","S1041120",
rep("S1042529",6), rep('S1235729',4))
column2 <- c(" T6-R190116","T2-R190213" ,"T8-R190118",
rep("T8-R190118",3), rep('T2-R190118',3),rep('T6-R200118',4),'T1-R200118')
column3 <- c(rep("3S_DMSO",7),rep("uns_DMSO",5),rep("3s_DMSO",2))
output_1 <- c(664,292,1158,574,38,0,2850,18,74,8,10,0,664,30)
output_2 <- c(364,34,0,74,8,0,850,8,7,8,310,0,64,380)
df <-data.frame(column1,column2,column3,output_1,output_2)
#aggregate data by the same value in column 1, 2 and 3
new_df <- aggregate(cbind(df$output_1,df$output_2), by=list(Category=df$column1), FUN=sum)
write.table(new_df, file = "aggregatedDMSO.txt",sep="\t", row.names = F, col.names = T)
So
- How can I pass column 1, 2 and 3 the same time into the list? I tried & them together and it didn't work.
- Second greedy question: my real dataset will have a lot columns of output, is there another way than cbind hard code all their names? (yes for some cases I can
df[,all columns from a certain index]
, but other times I might need to omit a few columns)
Thank you, ML