Nasser Nasser - 12 days ago 6
R Question

How to use for loop in R

I have a CSV dataset (call it

data
) as follow:

CLASS CoverageT1 CoverageT2 CoverageT3
Gamma 90 80 75
Gamma 89 72 79
Gamma 92 86 75
Alpha 50 80 67
Alpha 53 78 60
Alpha 58 81 75


I would like to retrieve the unique classes and calculate the average for each coverage column.

What I've done so far is the following:

classes <- subset(data, select = c(CLASS))
unique_classes <- unique(classes)

for(x in unique_classes){
cove <- subset(data, CLASS == x , select=c(CoverageT1:CoverageT3))
average <- colMeans(cove)
print(cove)
}


As a result, I got the following results:

CoverageT1 CoverageT2 CoverageT3
1 90 80 75
3 92 86 75
4 50 80 67
6 58 81 75


I want to retrieve the coverage values based on each class and then calculate the average. When I print the retrieved coverage values, I get some rows and the other are missing!

Can someone help me solving this issue

Thanks

Answer

This is how I solved it:

coverage_all <- aggregate(coverage , list(class=data$CLASS), mean)